I am developing a command line script which runs in an infinite loop. After a while it causes a segmentation fault which I think is caused by memory leaks. I think I am correct, because after looking on the results produced by the ps command it looks like the memory used by the script constantly increases before the script crashes.
I have found this article, which states that one possible cause of memory leaks in command line php is the use of foreach loops, which create copies of arrays that are never unset. After some research it looks like that is the case. So I decided to replace all foreach loops with their for equivalents.
First question – is my reasoning correct?
Second one – what to do if I have an associative array to iterate and I would like to know the current key?
One way I can think of would be using array_walk(), other one – using combination of next() and key() functions in a for loop. Which approach wouldn’t leave me with memory leaks?
I will perform some tests and post the results after I’m done.
Secondary problem would be how to deal with iterable objects but that’s for later.
EDIT 1: There are some differing results from my tests so I’ll post something new after some more research.
Using next() and key() will not give you the memory leaks that foreach does. Foreach creates an “internal” copy of your array, and that copy is the memory leak problem. Using next() and key() does not create a copy – then you are working with the original data.
Yet another suggestion on how to solve this is to use array_keys() like this:
However, I believe your suggestion with next() and key() will be the most effective one – and probably give you the prettiest code too! 🙂