PHP array_search() Function
Topic: PHP Array ReferencePrev|Next
Description
The array_search()
function searches an array for a given value and returns the corresponding key if the value is found. If the value is found more than once, the first matching key is returned.
The following table summarizes the technical details of this function.
Return Value: | Returns the first corresponding key if value is found in the array, FALSE otherwise. |
---|---|
Changelog: | Since PHP 5.3.0, this function returns NULL if invalid parameters are passed to it, this also applies to all internal or built-in PHP functions. |
Version: | PHP 4.0.5+ |
Syntax
The basic syntax of the array_search()
function is given with:
The following example shows the array_search()
function in action.
Example
Run this code »<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");
// Searching array for a value
echo array_search("ball", $alphabets); // Prints: b
echo array_search("dog", $alphabets); // Prints: d
?>
Parameters
The array_search()
function accepts the following parameters.
Parameter | Description |
---|---|
value | Required. Specifies the value to search for. |
array | Required. Specifies the array to be searched. |
strict | Optional. Determines if strict comparison (=== ) should be used during the value search. Possible values are true and false . Default value is false . |
Note: In strict comparison (using strict equality ===
operator) value and data type must be equal, therefore in strict comparison integer 4 is not equal to string "4".
More Examples
Here're some more examples showing how array_search()
function actually works:
You can also use this function to find the index of a value in an array, like this:
Example
Run this code »<?php
// Sample array
$colors = array("red", "green", "blue", "yellow", "orange");
// Searching array for a value
echo array_search("red", $colors); // Prints: 0
echo array_search("blue", $colors); // Prints: 2
?>
The following example shows how strict search for a value actually works (notice the ""
).
Example
Run this code »<?php
// Sample array
$numbers = array(1, 2, "5", 7, 8, 5, 10, 12);
// Searching array for a value
echo array_search(5, $numbers); // Prints: 2
echo array_search(5, $numbers, true); // Prints: 5
?>