phpmemory-managementmemory-leaks

Simple array push in PHP exceeds allowed memory. (Allowed memory size of 33554432 bytes exhausted (tried to allocate 33554440 bytes) )


This code is part of a bigger program but I identified this as the problem. I simply need to get the same values at the same indexes of arrays and this is the code I have written:

$a1=array(1,1,2);
$a2=array(1,2);
$a3=array(1,1);
$a4=array(1,1,3);
$a5=array(1,1,1,1);

$same= array();
for($i=0; $i<3; $i++){
    while($a1[$i]==$a2[$i] && $a1[$i]==$a3[$i] && $a1[$i]==$a4[$i] && $a1[$i]==$a5[$i]){
        array_push($same, $a1[$i]);
    }
}
print_r($same);

and it gives me this error:

Allowed memory size of 33554432 bytes exhausted (tried to allocate 33554440 bytes)

Adding more memory here is not an option.


Solution

  • The problem is that your while loop runs infinitely.

    while($a1[$i]=$a2[$i]=$a3[$i]){

    You see the equal sign? You just assigned one value to another from right to left. If you want to check, if all of them are equal you can do as below:

    while($a1[$i] == $a2[$i] && $a1[$i] == $a3[$i] && $a2[$i] == $a3[$i]){

    Overall, I think the code can & should be improved. You should not limit your for loop to a hardcoded number. Rather, limit it to the smallest array length. There are many ways to fix this issue.

    Edit:

    Your while loop runs infinitely because when index $i is zero, all values are equal and it gets stuck in the while loop. Replace the while loop with if. This will solve the memory size error, but you should also check if the keys exist before comparing them.