开发者

how to check PHP array's value without index offset error in 1 IF

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.


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) {

}


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
}


Yes, with the boolean operator && ;)

if (isset($array[$key]) && ($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.


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
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜