The in_array()
function returns true if an array contains a specific value;
otherwise, it will return false:
PHP in_array() Function has the following syntax.
bool in_array ( mixed needle, array haystack [, bool strict] )
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.
Is an element in an array
<?PHP/*from ww w. ja va2s . c o m*/
$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.
Use strict checking
<?PHP/* www. j av 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.
The following code shows how to check if a number is in an array.
// w ww .j a v a 2s.com
<?php
$primes = array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47);
for($count = 1; $count++; $count < 1000) {
$randomNumber = rand(1,50);
if (in_array($randomNumber,$primes)) {
break;
} else {
echo "<p>Non-prime number encountered: $randomNumber</p>";
}
}
?>