Current Location: Home> Latest Articles> How to Find the Index of a Value in a PHP Array Using array_search

How to Find the Index of a Value in a PHP Array Using array_search

M66 2025-06-23

Introduction

In PHP, you can find the index (or key) of a specific value in an array using the built-in array_search() function. This function searches the array for a given value and returns the corresponding key. If the value is not found, it returns false.

Basic Usage

The syntax of the array_search() function is as follows:

<span class="fun">array_search($value, $array, $strict = false)</span>

Here, $value is the value you want to search for, $array is the array to search within, and $strict is an optional parameter. When set to true, strict type comparison is used.

Example

The following example demonstrates how to search for a value in an array and get its index:

$arr = array(2, 4, 8, 16, 32);
$key = array_search(8, $arr); // Returns 2
<p>$key = array_search(10, $arr); // Returns false<br>

Important Notes

Type Comparison

By default, array_search() uses loose comparison, meaning it may convert types during comparison. If you want to ensure strict comparison (no type conversion), pass true as the third argument.

Duplicate Values

If the array contains multiple matching values, array_search() will return the index of the first match only.

False vs. 0

If the value you're searching for is found at index 0, the function returns 0. If the value is not found, it returns false. To avoid confusion between these two cases, use strict comparison (e.g., ===) when checking the result.

Conclusion

The array_search() function offers a straightforward and effective way to find the index of a value in an array. Understanding how it handles comparison and return values will help you use it more reliably in real-world coding scenarios.