cytsunny cytsunny - 26 days ago 8
PHP Question

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

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.

Answer

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.

Comments