Skip to content
Advertisement

PHP exceeding memory allocation in nested loops

I am parsing a string. If it meets a certain criteria, I want to append the new character to another substring until it stops meeting that criteria, and / or the end of the string.

The code is basically as follows:

JavaScript

The error that follows is: PHP message: PHP Fatal error: Allowed memory size of 805306368 bytes exhausted (tried to allocate 20480 bytes)...

I don’t usually code in php or c where I have to worry about memory management, so a brief refresher as to what is happening and how to fix it would be great for in the future.

Help appreciated 🙂

Advertisement

Answer

I think the reason as to why this was throwing an error was because at some point the index doesn’t exist… so it shouldn’t be a memory allocation error, but rather a index doesn’t exist error… which means when I am in the while loop, before I check to see if the key exists as the substring (if (array_key_exists(implode("", array($substr , $text[$i + 1])), $objectsKeys))), I needed to check to make sure that the next character’s index was less than strlen($text); so… if ($i + 1 < strlen($text)) {...}, which means that I also had to add the else statement to make sure it would exit the while loop (else { $check = false; }) if $i + 1 was greater than the length of the text.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement