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:

//loop through all the text
for ($i = 0; $i < strlen($text); $i++) {
    //set a boolean to enter and exit the while loop
    $check = true;
    //get the first letter at the ith position
    $substr = $text[$i];
    //start the while loop
    while ($check)
    {
        //check to see if the next character added to the string will be in some group of object keys
        if (array_key_exists(implode("", array($substr, $text[$i + 1]), $objectsKeys)))
        {
            //if it is, append it to the substring
            $substr = implode("", array($substr, $text[$i + 1]));
            //increment i
            $i++;
            //and try the next character
        }
        else
        {
            //otherwise, exit the loop
            $check = false;
        }
    }
}

//set the "letter" to be the substring - not too important for the application...
$letter = $substr;

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