Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_search()

Example

Search an array for the value “red” and return its associated key.

<?php
$a=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”);
echo array_search(“red”,$a);
?>

Definition and Usage

The array_search() function searches an array for a value and returns the corresponding key.

Syntax

array_search(value, array, strict)

Parameter Values

 

Parameter

Description

value

Required. Specifies the value to search for.

array

Required. Specifies the array to search.

strict

Optional. If set to TRUE, the function will search for identical elements in the array. Possible values are:

  • true
  • false (default)

When set to true, the number 5 is not considered the same as the string “5” (see example 2).

Technical Details

Return Value:

Returns the key of a value if found in the array, or FALSE if not. If the value appears multiple times, only the first matching key is returned.

PHP Version:

4.0.5+

PHP Changelog:

This function returns NULL if invalid parameters are passed, which applies to all PHP functions from PHP 5.3.0 onwards.

 

In PHP 4.2.0 and earlier, this function returns FALSE on failure instead of NULL.

More Examples

Example

Search an array for the value 5 and return its key (note the use of quotation marks for the value).

<?php
$a=array(“a”=>“5”,“b”=>5,“c”=>“5”);
echo array_search(5,$a,true);
?>