Reputation: 1350
I'm going over some problems from CodeEval and running into this strange error in PHP. I haven't run into anything like this with other languages, so I'm at a loss as to why this would happen. Without including the whole answer (and please don't help me find the solution, other than why PHP is acting this way), here's where I'm running into problems:
for ($j = 0; $j < count($beauty); $j++) {
$temp = $beauty[$j];
$beauty[$j] = $beauty[$j+1];
$beauty[$j+1] = $temp;
}
Essentially I've gotten a count of each individual letter and am now going to sort the array holding those values so I can determine the "beauty" of the string. Strange thing is I get the error:
Allowed memory size of 134217728 bytes exhausted
When running the above block of code. Even stranger, when I take out that final line in the for loop I stop getting the error.
for ($j = 0; $j < count($beauty); $j++) {
$temp = $beauty[$j];
$beauty[$j] = $beauty[$j+1];
}
Will work just fine, I just can't solve the problem that way. I was thinking maybe there was some strange thing, like PHP was passing the values in the array by reference, or passing values of variables in general by reference and maybe that was causing problems, but I don't see that that's the case. I can't see why setting the value of the following array position to the value I've stored in $temp would cause the program to eat up that much memory. The loop in this case is only for an array with a count of 19. I can't imagine how 19 integers are taking up 128Mb of space in memory, even if we're doing a swap on each pass.
Anyone know why this is happening?
Upvotes: 1
Views: 514
Reputation: 5803
You are creating an infinite loop at this line:
$beauty[$j+1] = $temp;
since in every iteration of the $beauty
loop you are adding a new element your loop will never complete
Upvotes: 3