I have a set of objects I want to put into an array and I want to distinguish them with keys.
The initial code I wrote was:
array_push($array[$key], new myObj(param1, param2, etc));
When I run it I get the warning:
PHP Warning: array_push() expects parameter 1 to be array, null given in file.php on line 56
I added a var_dump() to see what was actually happening and it was filling the array with each element ‘$key => null’ as suggested by the error.
If I remove the [$key] from the line then it fills the array with instances of myObj as expected so I know that the constructor is functioning correctly and not really returning ‘null’.
Keys in associative arrays need to be unique, so if you want to keep the notion of a key/value pair where you can access things directly by the key, don’t use
array_push, simply set the key (this is fine to do in PHP):On the other hand, if you want to have a list of key/value pairs, like a stack, and you’re adding just one key/value pair at a time, don’t use
array_push, simply add to the array using PHP’s shorthand syntax (as the manual says, this is faster as it saves you a function call):One more possibility, if you have a bunch of key/value pairs, and you want to add all of them to some stack like structure (but not be able to index directly by some key), then you should use
array_push: