PHP array_search() Function
The PHP array_search() function searches an array for a specific value and returns the first corresponding key if found. It performs a loose or strict search based on parameters and returns false if the value is not present in the array.
Syntax
array_search($value, $array, strict_parameter)
Parameters: This function takes three parameters as described below:
- $value: This is the mandatory field that refers to the value that needs to be searched in the array.
- $array: This is the mandatory field that refers to the original array, which needs to be searched.
- strict_parameter (optional): This is an optional field that can be set to TRUE or FALSE, and refers to the strictness of search. The default value of this parameter is FALSE.
- If TRUE, then the function checks for identical elements, i.e., an integer 10 will be treated differently from a string 10.
- If FALSE, strictness is not maintained.
Return Value: The function returns the key for a given value. If not found, it returns `false`; if multiple matches, the first key.
Example: In this example we defines a function Search() that uses array_search() to find the first occurrence of the value "saran" in the array. It returns the index of the first match, which is 2.
<?php
// PHP function to illustrate the use of array_search()
function Search($value, $array)
{
return (array_search($value, $array));
}
$array = array(
"ram",
"aakash",
"saran",
"mohan",
"saran"
);
$value = "saran";
print_r(Search($value, $array));
?>
Output
2
Example: This example illustrates the working of function when the strict_parameter is set to FALSE. Note that the data types of the array and to be searched elements are different.
<?php
// PHP function to illustrate the use of array_search()
function Search($value, $array)
{
return (array_search($value, $array, false));
}
$array = array(
45, 5, 1, 22, 22, 10, 10);
$value = "10";
print_r(Search($value, $array));
?>
Output
5
Example: In this example, we will be utilizing the above code to find out what will happen if we pass the strict_parameter as TRUE.
<?php
// PHP function to illustrate the use of array_search()
function Search($value, $array)
{
return (array_search($value, $array, true));
}
$array = array(45, 5, 1, 22, 22, 10, 10);
$value = "10";
print_r(Search($value, $array));
?>
Output