0

I need to push a new object into an array when it doesn't exist in the array. but I keep receiving this error. I read this often occurs when creating new objects in a loop or pushing items onto an array in a loop. I've attempted to reuse the objects and just reset the member values but I still get the same errors. What is the best way to accomplish this?

Error:

PHP Fatal error:  Allowed memory size of 67108864 bytes exhausted (tried to allocate 71 bytes)

Code:

if(!array_key_exists($a->name, $tArray)) $tArray[] = $a;
3
  • view this: stackoverflow.com/questions/561066/… Commented Mar 27, 2013 at 19:25
  • Be advised, objects are passed by reference not value. So reusing the object and changing its properties would change what all existing references in the array point to. In order to overcome this when looping through objects and pushing them to an array you need to use the clone method to instantiate a new object. Otherwise, your array will contain references all to the same object. For more help see this article. Commented Mar 27, 2013 at 19:30
  • Maetschl, comment solved my issue. Commented Mar 27, 2013 at 19:42

1 Answer 1

3

You have a bug. Do this:

if(!array_key_exists($a->name, $tArray)) $tArray[$a->name] = $a;

Otherwise array_key_exists will always return false and always add $a to it.

Sign up to request clarification or add additional context in comments.

3 Comments

It's important to note that each time the OP loops through and "reuses" an existing object, it needs to be cloned to prevent all the references throughout the array from changing. This is due to the fact that objects are passed by reference not value.
That is originally how I tried to do this but I get this error: Maximum execution time of 30 seconds exceeded
I was creating two new objects per loop iteration. The loop was iterated about 10-15 times.

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.