What is the best method for memory cleanup in PHP? (5.2)

Michal Drozd picture Michal Drozd · Aug 5, 2010 · Viewed 10.9k times · Source

I have two simple questions. What is better/useful for memory cleanup.

$var = null;

or

unset($var);

I have one function with one cycle. I am getting (after few minutes)

Fatal error: Allowed memory size of 419430400 bytes exhausted

I am setting null and unset()-ing every object (at the end of the cycle) but still without any success :( I cant find out what is consuming memory.

And what about function calls in cycle? Will PHP release all allocations in these functions?(after call)

Answer

Álvaro González picture Álvaro González · Aug 5, 2010

PHP itself confuses both concepts sometimes but, in general, a variable set to NULL is not the same as a variable that does not exist:

<?php

$foo = 'One';
$bar = 'Two';

$foo = NULL;
unset($bar);

var_dump($foo); // NULL
var_dump($bar); // Notice: Undefined variable: bar
var_dump(get_defined_vars()); // Only foo shows up: ["foo"]=> NULL

?>