Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP array_search() Function

PHP array_search() Function

PHP Array ReferenceComplete PHP Array Reference Manual

Example

Search an array for the value "red" and return its key:

"red" , "b" => "green" , "c" => "blue" ) ; echo array_search ( "red" , $a ) ; ?>

Run Example »


Definition and Usage

The array_search() function searches an array for a given value and returns the corresponding key. If the value is not found, it returns false.


Syntax

array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

Parameters Description
$needle Required. Specifies the value to search for in the array.
$haystack Required. Specifies the array to search.
$strict Optional, default is false, which compares values only, not types. If set to TRUE, the function searches the array for an element with both the same data type and value. Possible values:
  • true
  • false - Default
  • If set to true, the type of the given value is checked in the array; the number 5 and the string 5 are different (see Example 2). |

    Technical Details

    Return Value: If the specified value is found in the array, returns the corresponding key, otherwise returns FALSE. If the value is found more than once, the key of the first match is returned.
    PHP Version: 4.0.5+
    Changelog: If invalid arguments are passed to the function, it returns NULL (this applies to all PHP functions since PHP 5.3.0).
     自 PHP 4.2.0 起,如果搜索失败,该函数返回 FALSE,而不是 NULL。 |
    
    

    More examples

    Example

    Example 1

    Search an array for the value 5 and return its key (note ""):

    "5" , "b" => 5 , "c" => "5" ) ; echo array_search ( 5 , $a , true ) ; ?>

    Run Example »


    PHP Array ReferenceComplete PHP Array Reference Manual