I have a foreach statement in my code, where each iteration calculates huge amounts of data and goes to the next iteration. I run this code, but when I read the log, I see there’s a memory leak error.
PHP.net says when this happens, using gc_enabled() is a good way to handle this.
I’ve added these lines to last line of the foreach block:
echo "Check GC enabled : " . gc_enabled();
echo "Number of affected cycles : " . gc_collect_cycles();
And this is the output:
Check GC enabled : 1
Number of affected cycles : 0
Why do cycles exist, but the affected cycles is 0?
Chances are you didn’t see “memory leak error”, you don’t just see those. What you saw is probably the allowed memory exhausted error, which means that your script went over the allowed maximum memory limit that’s defined in php.ini. To change the limit, look at the manual page for core php.ini directives. You’ll find
memory_limitunder Resource Limits.As for
gc_collect_cycles(), the function is still undocumented, which is a good hint to not use it. What you read is probably the theory behind collecting cycles in PHP. What the function reports is that there weren’t any cycles collected, which probably means no memory leak error message in the first place.I would suggest you avoid garbage collection in PHP until it gets properly documented and you understand the basics involved.