When should isset () be used in an array without specifying a key?

I found out that isset($array) not required when checking for a specific key, however I also know that there are some reasons for checking without a known key if $array is created.

For instance:

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

PHP Note: Undefined variable: foo
PHP Warning: invalid argument provided by foreach ()

it's better:

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

Since I use arrays a lot when working with data, and I wanted to ask if there are other cases when I have to check if the entire isset() array exists? Or should I just check every $array[$key] that I will use when it is known? This is related to the question of whether there are any advantages or disadvantages in doing so:

 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) instead of isset($array[$key]) if $key is known?

+6
source share
2 answers

In PHP, isset() is a special form, not a function; when you call isset($ary[$index]) , you do not need to set $ary . Even with E_STRICT call will not generate a warning because isset is not actually trying to access $ary[$index] ; it comes to the determination that $ary not installed and returns false . Therefore, you do not need to check the array first to apply isset to the element.

Your question indicates that you already know this, and are wondering if there is a reason why you will do this. The only thing I can think of is efficiency: if you are going to check a large number of keys for existence in an array, you can save some work by first discovering when the array itself is not installed, and just skip everything; in this case, the individual key is checked.

+15
source

If you want to know if an array is defined, use isset($array) .

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

For example, this is perfectly true:

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

Source: https://habr.com/ru/post/913885/


All Articles