The in_array()
function in PHP checks if a value exists in an array. It returns true
if the value is found, and false
if it is not.
Syntax:
in_array($needle, $haystack, $strict);
- $needle: The value to search for in the array.
- $haystack: The array in which to search for the value.
- $strict (optional): If set to
true
, it will also check the types of the $needle
and array elements. If false
(default), it will only check the value, ignoring types.
Examples:
Example 1: Basic usage
$fruits = ["apple", "banana", "cherry"];
if (in_array("banana", $fruits)) {
echo "Banana is in the array.";
} else {
echo "Banana is not in the array.";
}
Output:
Banana is in the array.
Example 2: Strict comparison
$numbers = [1, 2, 3, "4"];
if (in_array(4, $numbers, true)) { // strict comparison enabled
echo "4 is in the array.";
} else {
echo "4 is not in the array.";
}
Output:
4 is not in the array. // because 4 as an integer is different from "4" as a string
Example 3: Searching for a string in an array of strings
$names = ["John", "Jane", "Doe"];
if (in_array("Jane", $names)) {
echo "Jane is in the array.";
} else {
echo "Jane is not in the array.";
}
Output:
Jane is in the array.
Example 4: Case-sensitive search
$colors = ["Red", "Blue", "Green"];
if (in_array("red", $colors)) {
echo "Red is in the array.";
} else {
echo "Red is not in the array.";
}
Output:
Red is not in the array. // case-sensitive comparison
This function is handy when you need to check the existence of a value in an array without manually looping through it.