php, key check on NULL variable gets set, how to?

78 views Asked by At

here is my example:

$data = null;

var_dump($data); // returns null

is($data['test']);

var_dump($data); // returns array (size=1)
                 //            'test' => null

function is(&$var, $default = null)
{
    return isset($var) ? $var : $default;
}

notice that after I run is($data['test']), $data becomes $data['test'] = null

any ideas why this behavior?

I am looking to get null. I am running php 7

edit: it's the & symbol, just not sure why would yield that result

3

There are 3 answers

1
masterFly On BEST ANSWER

You cannot pass a variable with a non existing key to a function (even with reference) since the value will be passed to the function.

If we have $data and in the next line if we do $data['test'], the $data variable will be updated to an array.

So in your case, when you use is($data['test']);, it updates the variable.

Then it goes to the function, and checks isset($var). It is already set since the variable is updated already. So the isset gets a true return. That return will contain the updated variable which is $data['test'].

I think the solution from @Fred B will work in this case.

0
Hadi Susanto On

try using array_key_exists() and return null if key not found.

1
Fred B On

This solution seems to work, though less elegant:

is($data, 'test');

var_dump($data); // returns array (size=1)
                 //            'test' => null

function is($var, $key, $default = null)
{
    return isset($var[$key]) ? $var[$key] : $default;
}