PHP in_array() Function
In this chapter you will learn:
- Definition for PHP in_array() Function
- Syntax for PHP in_array() Function
- Parameter for PHP in_array() Function
- Example - Is an element in an array
- Example - Use strict checking
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/* j a v a 2 s . c om*/
$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 j a va 2s. c om
$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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP key() Function
- Syntax for PHP key() Function
- Parameter for PHP key() Function
- Return value for PHP key() Function
- Example - Return the element key from the current internal pointer position
Home » PHP Tutorial » PHP Array Functions