对于清除或未设置的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:42:41  来源:igfitidea点击:

For cleared or unset php arrays, are elements garbage collected?

phparrays

提问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 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

拼接文档