Checking if a value exists in array is frequently used in php. PHP in_array() can be used for this check. By default it does not do a strict check. So a string will match with number if same.
in_array without strict
Here string ‘123’ will match with number 123.
<?php $a = array('abc', 123); if (in_array('123', $a)) { print "FOUND\n"; } else { print "NOT_FOUND\n"; } ?>
FOUND
Env: PHP 7.4.33 (Linux)
in_array with strict
Here string ‘123’ will not match with number 123.
<?php $a = array('abc', 123); if (in_array('123', $a, TRUE)) { print "FOUND\n"; } else { print "NOT_FOUND\n"; } ?>
NOT_FOUND
Env: PHP 7.4.33 (Linux)
in_array and associative array
Here in_array only checks in values (not keys).
<?php $a = array('k1'=>'abc', 'k2'=>123); if (in_array('abc', $a)) { print "FOUND\n"; } else { print "NOT_FOUND\n"; } if (in_array('k1', $a)) { print "FOUND\n"; } else { print "NOT_FOUND\n"; } ?>
FOUND NOT_FOUND
Env: PHP 7.4.33 (Linux)