如何在1 IF中检查没有索引偏移错误的PHP数组值

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

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

(sorry, accidentally put ! in first IF originally)

The && operator is short-circuit, thus:

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

Happy coding.

Yes, with the boolean operator && ;)

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

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

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

You may also use a reference: if $array[$key] does not exist, then it will be created and set to null; therefore, no error will occur. This is most useful when you expect the value to exist; ie, you do not want to act specially if the value does not.

if (&$array[$key] == $x) {

}

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

if(sizeof($array) >= $key){

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

}

Best approach is using array_key_exists() function.

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

Check the documentation link more details.