Home » Php » php – When isset() should be used on Array without specifying key?

php – When isset() should be used on Array without specifying key?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have learned that isset($array) is not required when checking for existence of particular key, however I also know that there is some reasons to check, without known key, if $array is instantiated.

For example this:

foreach ($foo as $bar) {
    echo $bar;
}

PHP Notice: Undefined variable: foo
PHP Warning: Invalid argument supplied for foreach()

is better this way:

if (isset($foo)) {
    foreach ($foo as $bar) {
    echo $bar;
    }
}

As I use arrays a lot when dealing with data and I wanted to ask if there is some other cases where i should check if whole array isset()? Or should I just stick on checking every $array[$key] that I am going to use whenever known?
This relates to question if there is any advantages or disadvantages on doing this:

if (isset($foo[0])) {
    foreach ($foo as $bar) {
        // noop
    }
}

instead of this:

if (isset($foo)) {
    foreach ($foo as $bar) {
        // noop
    }
}

So, should I ever use isset($array) in place of isset($array[$key]) if $key is known?

How to&Answers:

In PHP, isset() is a special form, not a function; when you call isset($ary[$index]), $ary itself doesn’t have to be set first. Even with E_STRICT, the call won’t generate a warning, because isset doesn’t actually try to access $ary[$index]; it gets as far as determining that $ary is not set and returns false. So you don’t need to check the array first in order to apply isset to an element.

Your question indicates that you know this already, and are wondering if there’s a reason why you would do it anyway. The only thing I can think of is efficiency: if you’re going to be checking a large number of keys for existence in an array, you can save some work by first detecting when the array itself isn’t set, and just skipping all the individual key checks in that case.

Answer:

If you want to know whether the array is defined at all, use isset($array).

If you want to know whether a particular key is defined, use isset($array[$key]).

For instance, this is perfectly valid:

$foo = array();
foreach($foo as $bar) {
    // never called because $foo is an empty array
}