Home >Backend Development >PHP Tutorial >Detailed explanation of the use of php array_search() function

Detailed explanation of the use of php array_search() function

藏色散人
藏色散人Original
2019-04-23 14:08:224546browse

The array_search() function is a built-in function of PHP that is used to search for a specific value in an array. If the value is found, it will return the corresponding key. If there are multiple values, the key of the first matching value is returned.

Syntax:

array_search($value, $array, strict_parameter)

Parameters:

This function has three parameters, as follows:

$value (required): Reference to the value to be searched for in the array.

$array (required): refers to the original array to be searched.

strict_parameter (optional): can be set to TRUE or FALSE to indicate the strictness of the search. The default value for this parameter is FALSE.

If TRUE, the function checks for the same elements, i.e. the integer 10 will be treated differently than the string 10.

If FALSE, no strictness is maintained.

Return value:

As mentioned before, the function returns the key of the corresponding value passed. If not found, returns FALSE; if there are multiple matches, returns the first matching key.

Usage example of array_search() function in PHP:

<?php 

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 following program, we will see that when strict_parameter is set to How the function works when FALSE. Note that the data type of the array is different from the data type of the element being searched.

<?php 
  
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 see what happens if we pass strict_parameter as TRUE to the same program.

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

Related recommendations: "PHP Tutorial"

The above is the detailed content of Detailed explanation of the use of php array_search() function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn