cytsunny cytsunny - 1 year ago 50
PHP Question

Is there a function like in_array that will check for empty values in PHP?

It is known that

function can be used to check if an array contains a certain value. However, when an array contains the value
, an empty or
values pass the test, too.

For example

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

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

I know I can solve the problem by adding an extra
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download