php function to unset variables passed by reference

Viewed 8126

currently i'm using this php function :

function if_exist(&$argument, $default = '')
{
    if (isset ($argument))
    {
        echo $argument;
    }
    else
    {
        echo $default;
    }
}

i want this function to unset the variables $argument(passed by reference) and $default just after echoing their value, how can i do this? Thanks in advance.

4 Answers

If var is not array, and passed by reference, unset is actually unset the pointer, so it will not affect the original.

However if the var is array, you can unset its keys. eg:

$arr = [
    'a' => 1, 
    'b' => ['c' => 3],
];

function del($key, &$arr) {
    $key = explode('.', $key);
    $end = array_pop($key);
    foreach ($key as $k) {
        if (is_array($arr[$k]) {
            $arr = &$arr[$k];
        } else {
            return; // Error - invalid key -- doing nothing
        }
    }
    unset($arr[$end]);
}

del('b.c', $arr); // $arr = ['a' => 1, 'b' => []]
del('b',   $arr); // $arr = ['a' => 1]
Related