How to check PHP array value without index offset error in 1 IF

Is it possible to check the value of a specific key in a PHP array in a 1 IF statement? Right now, so as not to throw an index offset error, I have to check if the key is installed, and then check its value.

if (isset($array[$key])) { if ($array[$key] == $x) { // do stuff } } 

(sorry, accidentally set! in the first IF initially)

+6
arrays php
source share
6 answers

The && operator is a short circuit , thus:

 if (isset($array[$key]) && $array[$key] == $x) // do stuff } 

Happy coding.

+6
source share

You can also use the link: if $array[$key] does not exist, then it will be created and set to null; therefore there will be no error. This is most useful when you expect a value to exist; those. you do not want to act on purpose if this value does not matter.

 if (&$array[$key] == $x) { } 
+3
source share

try it. ur current code will not do anything bc if it is not installed, the second if statement will never be ...

 if (isset($array[$key]) && $array[$key] == $x) { //do stuff if that key == $x } 
+2
source share

Yes, with the boolean operator && ;)

 if (isset($array[$key]) && ($array[$key] == $x)) { // do stuff } 
+1
source share

A better approach is to use the array_key_exists() function.

An example is array_key_exists($key,$array);

See the documentation for more details.

+1
source share

if you have an associative array, compare the size of the array with the key index instead of $ key

 if(sizeof($array) >= $key){ if ($array[$key] == $x) { // do stuff } } 
0
source share

All Articles