array_search() function in PHP


The array_search() function searches an array for a given value and returns the key. The function returns the key for val if it is found in the array. It returns FALSE if it is not found. If val is found in the array arr more than once, then the first matching key is returned.

Syntax

array_search(val, arr, strict)

Parameters

  • val − The value to be searched

  • arr − The array to be searched

  • strict − Possible values are TRUE or FALSE. Search for identical elements in the array, set to TRUE.

Return

The array_search() function returns the key for val if it is found in the array. It returns FALSE if it is not found. If val is found in the array arr more than once, then the first matching key is returned.

Example

The following is an example −

 Live Demo

<?php
$arr = array("p"=>20,"q"=>20,"r"=>30,"s"=>40);
echo array_search(20,$arr,true);
?>

Output

The following is the output −

p

Example

Let us see another example −

 Live Demo

<?php
$arr = array(30, 2, 5, 7, 90, 35, 78);
echo array_search(35,$arr,true);
?>

Output

The following is the output −

5

Example

Let us see another example with array having string values −

 Live Demo

<?php
$arr = array("MAC", "WINDOWS","LINUX", "SOLARIS");
$search = "WINDOWS";
echo array_search($search,$arr,true);
?>

Output

The following is the output −

1

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Sep-2023

26K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements