对于清除或未设置的 php 数组,元素是否被垃圾收集?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5527541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For cleared or unset php arrays, are elements garbage collected?
提问by user678070
if I unset an array, would its elements be garbage collected or freed up assuming they are not referenced in anywhere else? what if I simply do $array =new array();
如果我取消设置一个数组,它的元素是否会被垃圾收集或释放,假设它们没有在其他任何地方被引用?如果我只是简单地做 $array =new array();
$array = array('a'=>1); //method 1 to clear array unset($array);
method 2 to clear an array
方法二清空数组
$array = array('a'=>1); //method 2 to clear array $array y = array();
采纳答案by Johann du Toit
Check-out php < 5.3 garbage collection, do array values need to be set null or does setting the array = null orphan all its elements?, maybe that will help answer your question.
检出php < 5.3 垃圾收集,是否需要将数组值设置为 null 或设置 array = null 是否孤立其所有元素?,也许这将有助于回答您的问题。
回答by forsberg
Following simple code answers the question:
以下简单代码回答了这个问题:
$a = array();
$a[0] = 'a1';
$a[1] = 'b2';
foreach($a as $v)
echo $v . '<br />';
//writes content of array
echo count($a) . '<br />';
//writes 2
$a = array(); //CLEAR ARRAY
foreach($a as $v)
echo $v . '<br />';
//writes nothing
echo count($a) . '<br />';
//writes 0
回答by LopSae
The following will modify the array itself and leave it empty:
以下将修改数组本身并将其留空:
array_splice($myArray, 0);
And the Splice Documentation
和拼接文档