PHP in_array() Function
Definition
The in_array()
function returns true if an array contains a specific value;
otherwise, it will return false:
Syntax
PHP in_array() Function has the following syntax.
bool in_array ( mixed needle, array haystack [, bool strict] )
Parameter
Parameter | Is Required | Description |
---|---|---|
search | Required. | What to search for |
array | Required. | Array to search |
type | Optional. | Use strict checking |
The optional boolean third parameter for in_array()
(set to false by default)
defines whether to use strict checking.
If parameter three is set to true, PHP will the ===
operator to do the search.
Example 1
Is an element in an array
<?PHP//w w w . ja va 2s . com
$needle = "java2s.com";
$haystack = array("A", "java2s.com", "B", "C", "D", "E");
if (in_array($needle, $haystack)) {
print "$needle is in the array!\n";
} else {
print "$needle is not in the array\n";
}
?>
The code above generates the following result.
Example 2
Use strict checking
<?PHP/*from w w w . j a v a 2 s . c o m*/
$needle = 5;
$haystack = array("5", "java2s.com", "B", "C", "D", "E");
if (in_array($needle, $haystack,true)) {
print "$needle is in the array!\n";
} else {
print "$needle is not in the array\n";
}
if (in_array($needle, $haystack,TRUE)) {
print "$needle is in the array!\n";
} else {
print "$needle is not in the array\n";
}
?>
The code above generates the following result.