Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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 = 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();
like image 1000
user678070 Avatar asked Apr 03 '11 04:04

user678070


People also ask

Does PHP use garbage collection?

As of PHP 7.3, PHP provides basic garbage collection information in user land PHP, via gc_status. The function returns: The number of garbage collection runs. The number of objects collected.

How do you clear an array in PHP?

Basic example of empty array:$emptyArray = ( array ) null; var_dump( $emptyArray );

What is the function name in PHP used to delete an element from an array?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array.


2 Answers

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
like image 131
forsberg Avatar answered Oct 15 '22 18:10

forsberg


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.

like image 35
Johann du Toit Avatar answered Oct 15 '22 17:10

Johann du Toit