1

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'.

1
  • Not sure what the etiquette is here, but the wording on this question and its conciseness makes it far more readable/searchable than the candidate dupe. I'd prefer to make the old one a dupe of this one, honestly. Commented Jan 23, 2011 at 4:43

2 Answers 2

3

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):

$array[$key] = new myObj(param1, param2, etc)

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):

$stack[] = array($key => new myObj(param1, param2, etc));

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:

array_push($stack,
    array($key1 => new myObj(param1, param2, etc)),
    array($key2 => new myObj(param3, param4, etc))
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick response! I actually found the answer myself (here). I failed to do a search before posting. stackoverflow.com/questions/3481584/…
0

Try:

$array[$key] = new myObj(param1, param2, etc);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.