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
}
}
In PHP,
isset()is a special form, not a function; when you callisset($ary[$index]),$aryitself doesn’t have to be set first. Even withE_STRICT, the call won’t generate a warning, becauseissetdoesn’t actually try to access$ary[$index]; it gets as far as determining that$aryis not set and returnsfalse. So you don’t need to check the array first in order to applyissetto 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.