Programming

PHP 배열의 값을 지우는 가장 좋은 방법

procodes 2020. 6. 4. 21:18
반응형

PHP 배열의 값을 지우는 가장 좋은 방법


배열의 모든 값을 지우는 데 더 효과적인 것은 무엇입니까? 첫 번째는 두 번째 예제의 루프에서 매번 해당 기능을 사용해야합니다.

foreach ($array as $i => $value) {
    unset($array[$i]);
}

아니면 이거

foreach($blah_blah as $blah) {
    $foo = array();
    //do something
    $foo = null;
}

Zack이 아래 주석에서 말했듯이 간단히 사용하여 다시 인스턴스화 할 수 있습니다

$foo = array(); // $foo is still here

더 강력한 무언가를 원한다면 기호 테이블에서 $ foo를 지우므로 나중에 배열을 다시 인스턴스화해야합니다.

unset($foo); // $foo is gone
$foo = array(); // $foo is here again

변수를 빈 배열로 재설정하려면 간단히 다시 초기화하면됩니다.

$foo = array();

이것에 대한 참조가 유지됩니다.

$foo = array(1,2,3);
$bar = &$foo;
// ...
$foo = array(); // clear array
var_dump($bar); // array(0) { } -- bar was cleared too!

참조를 끊으려면 먼저 설정을 해제하십시오.

$foo = array(1,2,3);
$bar = &$foo;
// ...
unset($foo); // break references
$foo = array(); // re-initialize to empty array
var_dump($bar); // array(3) { 1, 2, 3 } -- $bar is unchanged

슬프게도 나는 다른 질문에 대답 할 수없고, 명성이 충분하지 않지만, 나에게 매우 중요한 것을 지적해야하며, 그것이 다른 사람들에게도 도움이 될 것이라고 생각합니다.

원래 배열의 참조가 필요하지 않으면 변수를 설정 해제하는 것이 좋습니다 .

의미하는 바를 분명히하기 위해 : 함수가 있다면 배열의 참조를 사용합니다 (예 :

function special_sort_my_array(&$array)
{
    $temporary_list = create_assoziative_special_list_out_of_array($array);

    sort_my_list($temporary_list);

    unset($array);
    foreach($temporary_list as $k => $v)
    {
        $array[$k] = $v;
    }
}

그것은 작동하지 않습니다! 여기서주의 unset하여 참조를 삭제하므로 변수 $array가 다시 작성되고 올바르게 채워지지만 함수 외부에서는 값에 액세스 할 수 없습니다.

따라서 참조 가있는 경우 덜 깨끗하고 이해하기 쉽더라도 $array = array()대신 대신 사용해야 합니다 unset.


배열이 연관되어 있다면 첫 번째라고 말하고 싶습니다. 그렇지 않은 경우 for루프를 사용하십시오 .

for ($i = 0; $i < count($array); $i++) { unset($array[$i]); }

가능하다면

$array = array();

배열을 빈 배열로 재설정하는 것이 좋습니다.


아니다 unset()충분한은?

unset($array);

어때요 $array_name = array();?


Use array_splice to empty an array and retain the reference:

array_splice($myArray, 0);


i have used unset() to clear the array but i have come to realize that unset() will render the array null hence the need to re-declare the array like for example

<?php 
    $arr = array();
    array_push($arr , "foo");
    unset($arr); // this will set the array to null hence you need the line below or redeclaring it.
    $arr  = array();

    // do what ever you want here
?>

I see this questions is realla old, but for that problem I wrote a recursive function to unset all values in an array. Recursive because its possible that values from the given array are also an array. So that works for me:

function empty_array(& $complete_array) {
    foreach($complete_array as $ckey => $cvalue)
    {
        if (!is_array($cvalue)) {
            $complete_array[$ckey] = "";
        } else {
            empty_array( $complete_array[$ckey]);
        }

    }
    return $complete_array;

}

So with that i get the array with all keys and sub-arrays, but empty values.


The unset function is useful when the garbage collector is doing its rounds while not having a lunch break;

however unset function simply destroys the variable reference to the data, the data still exists in memory and PHP sees the memory as in use despite no longer having a pointer to it.

Solution: Assign null to your variables to clear the data, at least until the garbage collector gets a hold of it.

$var = null;

and then unset it in similar way!

unset($var);

Maybe simple, economic way (less signs to use)...

$array = [];

We can read in php manual :

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].


This is powerful and tested unset($gradearray);//re-set the array

참고URL : https://stackoverflow.com/questions/10261925/best-way-to-clear-a-php-arrays-values

반응형