PHP in_array() Function
The PHP in_array() function checks if a value exists in an array. The function returns true if the value is found in the array, else returns false. The comparison is done in a case-sensitive manner.
Syntax
in_array(search, array, strict)
Parameters
search |
Required. Specify the searched value. |
array |
Required. Specify the array to search. |
strict |
Optional. If this parameter is set to true then the in_array() function will also check the types of the searched value in the array. |
Return Value
Returns true if the value is found in the array, else returns false.
Exceptions
NA.
Example:
The example below shows the usage of in_array() function.
<?php $Arr = array("Red", "Green", "Blue"); //checking "Blue" in the array if(in_array("Blue", $Arr)){ echo "Blue is found.\n"; } else { echo "Blue is not found.\n"; } //checking "red" in the array if(in_array("red", $Arr)){ echo "red is found.\n"; } else { echo "red is not found because case is not matched.\n"; } ?>
The output of the above code will be:
Blue is found. red is not found because case is not matched.
Example: using strict parameter
When the strict parameter is set to true, type of the value is also checked. Consider the example below:
<?php $Arr = array("1.5", 1.6, 1.7, 1.8); //checking 1.5 in the array if(in_array(1.5, $Arr)){ echo "1.5 is found.\n"; } else { echo "1.5 is not found.\n"; } //checking 1.5 in the array using strict parameter if(in_array(1.5, $Arr, true)){ echo "1.5 is found.\n"; } else { echo "1.5 is not found because type is not matched.\n"; } ?>
The output of the above code will be:
1.5 is found. 1.5 is not found because type is not matched.
Example: Searching array
In the example below, an array is searched in an array.
<?php $Arr = array(array(1, 2, 3), array(10, 20)); //checking array(1, 2) in the array if(in_array(array(1, 2), $Arr)){ echo "array(1, 2) is found.\n"; } else { echo "array(1, 2) is not found.\n"; } //checking array(1, 2, 3) in the array if(in_array(array(1, 2, 3), $Arr)){ echo "array(1, 2, 3) is found.\n"; } else { echo "array(1, 2, 3) is not found.\n"; } ?>
The output of the above code will be:
array(1, 2) is not found. array(1, 2, 3) is found.
❮ PHP Array Reference