Search code examples
phpfunctionarray-unset

Delete an element of array in function


I'm using some functions to delete vars. My code is like:

<?
$arr['var1'] = 'Hello';
$arr['var2'] = 'world';
function foo(){
    global $arr;
    unset($arr['var2']);
} 
foo();

But in the PHP manual:

To unset() a global variable inside of a function, then use the $GLOBALS array to do so:

unset($GLOBALS['arr']['var2']);

Doesn't unset anything because $GLOBALS['arr']['var2'] doesn't exist. I only want to unset GLOBAL array element inside function.

It exists, because GLOBALS are supervariable and it has everything other var has.

edit:

I tried to do it but after I try to call foo() then i try to print_r($arr) it show both var1 and var2, and if I try print_r($GLOBALS['arr']['var2']) it show undefined index.... Maybe it's be config...

edit2

I mistyped it in my script. So it's working...

Full working code:

<?
$arr['var1'] = 'Hello';
$arr['var2'] = 'world';
function foo(){
    global $arr;
    unset($GLOBALS['arr']['var2']);
} 
foo();

Solution

  • You can pass variable by reference:

    $arr['var1'] = 'Hello';
    $arr['var2'] = 'world';
    function foo(&$a){
        unset($a['var2']);
    }
    foo($arr);
    

    https://secure.php.net/manual/en/language.references.pass.php