pTutorial

New way to learn PHP function

PHP array search function

Syntax

array_search(search_value, $array [, option]);

Parameter Description
Search value Any data that you want to find (required)
Array Any array variable (required)
Option Option Default: false, match only vale not type and true for identical match

Definition

It returns the match value key of an array if element found otherwise it returns false.

Usage

array_search() function is used to find the element of an array and return its key. And after that you can access the element with help of key.

.

Note: Only the first instance of search value found returns its key. If the same Value is present later in the array, it is ignored.

Example of array search function

<?php

$num = array(20, 50, 10);

$key = array_search(50, $num); 

Print_r($num);

echo "
Key of search no: ".$key; ?>

In above example $num is an array variable that hold three element. You can search any data of array using the array_search() function as shown in above.

You can check the key with the help of print_r() function.

Example

<?php

$num = array(20, 50, 10);

var_dump( array_search('20', $num, TRUE) );

?>

Output

boolean false

If the third argument is set TRUE, array_search() will only return TRUE if the value and its variable type matches as well.

So in that case it return false because search element is string type.

More example of array search function

<?php

$fruit = array
(
10 => 'mango', 
20 => 'banana', 
30 => 'papaya',
 40 => 'grapes'
);

Print_r($fruit);

$key = array_search('grapes', $fruit); 

echo "
The key of ".$fruit[$key]."is : ". $key; ?>

$fruit is an associative array that hold four element, you can see with the help of print_r() function.

You can find the key of the searched array with the help of array_search() function and access.

QUOTES OF THE DAY

We are never deceived we deceive ourselves.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER