Home >Backend Development >PHP Tutorial >Instructions for using the php in_array function and instructions for what you need to pay attention to in_array
in_array
(PHP 4, PHP 5)
in_array — Check whether a certain value exists in the array
Description
bool in_array ( mixed $needle , array $haystack [, bool $strict ] )
Search for needle in haystack, if found, return TRUE, otherwise return FALSE.
If the value of the third parameter strict is TRUE, the in_array() function will also check whether the type of needle is the same as that in haystack.
Note: If needle is a string, the comparison is case-sensitive.
Note: Before PHP version 4.2.0, needle was not allowed to be an array.
Example #1 in_array() example
<?php $os = array("Mac", "NT", "Irix", "Linux"); if (in_array("Irix", $os)) { echo "Got Irix"; } if (in_array("mac", $os)) { echo "Got mac"; } ?>
The second condition fails because in_array() is case-sensitive, so the above program is displayed as:
Got Irix
Example #2 in_array() Strict type checking example
<?php $a = array('1.10', 12.4, 1.13); if (in_array('12.4', $a, true)) { echo "'12.4' found with strict check\n"; } if (in_array(1.13, $a, true)) { echo "1.13 found with strict check\n"; } ?>
The above example will output:
1.13 found with strict check
Example #3 in_array() using array as needle
<?php $a = array(array('p', 'h'), array('p', 'r'), 'o'); if (in_array(array('p', 'h'), $a)) { echo "'ph' was found\n"; } if (in_array(array('f', 'i'), $a)) { echo "'fi' was found\n"; } if (in_array('o', $a)) { echo "'o' was found\n"; } ?>
The above example will output:
'ph' was found
'o' was found
Things to note:
If:
First declare an array as:
$arr = array(*);
Then:
in_array(0, $arr) == true
It’s puzzling! {Weak language}
Solution:
in_array(strval(0), $arr, true))
For more php in_array function usage instructions and in_array notes, please pay attention to PHP Chinese for related articles net!