Check if array value isset and is null
Asked Answered
I

2

27

How to check if array variable

$a = array('a'=>1, 'c'=>null);

is set and is null.

function check($array, $key)
{
    if (isset($array[$key])) {
        if (is_null($array[$key])) {
            echo $key . ' is null';
        }
        echo $key . ' is set';
    }
}

check($a, 'a');
check($a, 'b');
check($a, 'c');

Is it possible in PHP to have function which will check if $a['c'] is null and if $a['b'] exist without "PHP Notice: ..." errors?

Illinium answered 20/7, 2013 at 21:56 Comment(1)
I don't get any notice warnings with your code.Locomotion
C
59

Use array_key_exists() instead of isset(), because isset() will return false if the variable is null, whereas array_key_exists() just checks if the key exists in the array:

function check($array, $key)
{
    if(array_key_exists($key, $array)) {
        if (is_null($array[$key])) {
            echo $key . ' is null';
        } else {
            echo $key . ' is set';
        }
    }
}
Coonskin answered 20/7, 2013 at 21:59 Comment(4)
@pulzarraider why did you replace is_null() with ===?Indenture
Because it's faster.Towill
@Towill - Any evidence to back up that claim? Because this post and this post seems to heavily disagree with you, saving nanoseconds at best and making your edit a superfluous micro-optimization.Coonskin
Yes, it's microoptimization, but why not make your function the fastest as it can be? Isset() is a bit slower because it's function call.Towill
E
-2

You may pass it by reference:

function check(&$array, $key)
{
    if (isset($array[$key])) {
        if (is_null($array[$key])) {
            echo $key . ' is null';
        }
        echo $key . ' is set';
    }
}

check($a, 'a');
check($a, 'b');
check($a, 'c');

SHould give no notice

But isset will return false on null values. You may try array_key_exists instead

Extensible answered 20/7, 2013 at 21:58 Comment(6)
The original code also doesn't give a notice. Passing by reference is unnecessary.Locomotion
@nickb, you post answer while I was checking if things I remember were right:)Extensible
It is what I wanted. Because of isset returning false on null I will do it like this: if(!isset($array[$key]) && is_null($array[$key])) which equals true if $array[$key] is null.Illinium
@BartekKosa your implementation is flawed. It will also return true and notice for keys that don't exists.Hendren
My final version would be if(is_null(...){ catch all nulls}elseif(isset(...)){ catch all set variables}. But the most important trick is passing an array by reference to get rid of "Notice".Illinium
Have you tested this? I believe isset() always returns false for null values even if they "exist" thus the is_null() will never be reached. The problem from the OP question remains.Stanleigh

© 2022 - 2024 — McMap. All rights reserved.