Tutorialspoint.dev

PHP | array_search() Function

This inbuilt function of PHP is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of first matching value will be returned.

Syntax:

array_search($value, $array, strict_parameter)

Parameters:
This function takes three parameters as described below:



  1. $value (mandatory): Refers to the value that needs to be searched in the array.
  2. $array (mandatory): Refers to the original array, which needs to be searched.
  3. strict_parameter (optional): 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 different from a string 10
    • If FALSE, strictness is not maintained.

Return Value: As already mentioned, the function returns the key of the corresponding value that is passed. If not found then FALSE is returned and if there are more than one matches, then the first matched key is returned.

Examples:

Input :  $array = ("ram", "aakash", "saran", "mohan", "aakash")
         $value = "aakash"
Output : 1

Input :  $array = (45, 5, 1, 22, 22, 10, 10)
         $value = 22
Output : 3

Below program illustrates the array_search() function in PHP:

<?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

In the below program, we will see how the function works when the strict_parameter is set to FALSE. Note that the data types of the array and to be searched element is 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

Now let’s find out what will happen if we pass the strict_parameter as TRUE, for the same program.

<?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:

No Output

Reference:
http://php.net/manual/en/function.array-search.php



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter