28

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?

1
  • 1
    I don't get any notice warnings with your code. Commented Jul 20, 2013 at 22:01

2 Answers 2

61

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';
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

@pulzarraider why did you replace is_null() with ===?
Because it's faster.
@pulzarraider - 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.
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.
-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

6 Comments

The original code also doesn't give a notice. Passing by reference is unnecessary.
@nickb, you post answer while I was checking if things I remember were right:)
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.
@BartekKosa your implementation is flawed. It will also return true and notice for keys that don't exists.
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".
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.