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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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)

How to&Answers:

The && operator is short-circuit, thus:

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

Happy coding.

Answer:

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

}

Answer:

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
}

Answer:

Yes, with the boolean operator && 😉

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

Answer:

Best approach is using array_key_exists() function.

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

Check the documentation link more details.

Answer:

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
    }

}