2

It is known that in_array() function can be used to check if an array contains a certain value. However, when an array contains the value 0, an empty or null values pass the test, too.

For example

<?php
    $testing = null;
    $another_testing = 0;
    if ( in_array($testing, [0,1,5,6,7]) )
        echo "Found";
    else
        echo "Not Found";
    echo "<br>";
    if ( in_array($another_testing, [0,1,5,6,7]) )
        echo "Found";
    else
        echo "Not Found";
?>

In both cases "Found" is printed. But I would like the first case to print "Not Found", and the second case - "Found".

I know I can solve the problem by adding an extra if statement, or by writing my own function, but I want to know if there are any built-ins in PHP that can perform the checks.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
cytsunny
  • 4,838
  • 15
  • 62
  • 129

1 Answers1

1

This behavior is explained by the fact that null == 0. But null !== 0. In other words, you should check for the types as well.

You don't need another function. Simply pass true as the third parameter:

in_array($testing, [0,1,5,6,7], true)

In this case in_array() will also check the types.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60