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

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -