php - more sophisticated adding value into an array -
i wonder, there elegant way add element in array, in situation don't know beforehand, whether want create new index or use existing one?
$array[$k] = $foo; // overwrites existing index, never creates 1 $array[] = $foo; // creates new one, never overwrites array_push(...); // creates new index $array[null] = $foo // sadly, null casted empty string
it nice this:
if($key === null) $array[] = $foo; else $array[$key] = $foo;
but fit in 1 expression
$array[!isset($key) || $key === null? count($array) : $key ] = $foo;
update: improved isset()
Comments
Post a Comment