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

Popular posts from this blog

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -