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

Winapi c++: DialogBox hangs when breaking a loop -

vb.net - Font adding using PDFsharp -

javascript - jQuery iScroll clickable list elements while retaining scroll? -