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;
ExceptionLimeCat
  • 6,191
  • 6
  • 44
  • 77
  • view this: http://stackoverflow.com/questions/561066/php-fatal-error-allowed-memory-size-of-134217728-bytes-exhausted-codeigniter – Maetschl Mar 27 '13 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](http://php.net/manual/en/internals2.opcodes.clone.php) method to instantiate a new object. Otherwise, your array will contain references all to the same object. For more help see [this](http://stackoverflow.com/questions/1064854/storing-objects-in-an-array-with-php) article. – War10ck Mar 27 '13 at 19:30
  • Maetschl, comment solved my issue. – ExceptionLimeCat Mar 27 '13 at 19:42

1 Answers1

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.

dlp
  • 430
  • 4
  • 9
  • 1
    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. – War10ck Mar 27 '13 at 19:34
  • That is originally how I tried to do this but I get this error: `Maximum execution time of 30 seconds exceeded` – ExceptionLimeCat Mar 27 '13 at 19:36
  • I was creating two new objects per loop iteration. The loop was iterated about 10-15 times. – ExceptionLimeCat Mar 28 '13 at 12:32