Backend Development 2 min read

Using PHP's array_search() to Locate a Value Within an Array

This article explains how PHP's array_search() function searches for a specified needle in a haystack array, describes its parameters—including the optional strict mode—and shows example code demonstrating how to retrieve the key of a matching element.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP's array_search() to Locate a Value Within an Array

Function Overview The array_search() function searches for a given needle value within a haystack array and returns the corresponding key if the value is found; otherwise it returns FALSE .

Parameters

needle (mixed): The value to search for in the array.

haystack (array): The array in which to search.

strict (bool, optional, default false ): When true , the function also checks that the type of the needle matches the type of the array element and that objects are the same instance.

Return Value If the needle is found, the function returns its key; otherwise it returns FALSE .

Example

<?php
$array = array(
    0 => 'blue',
    1 => 'red',
    2 => 'green',
    3 => 'red'
);

// Find the key of 'green'
$key = array_search('green', $array); // $key = 2;

// Find the key of 'red' (first occurrence)
$key = array_search('red', $array); // $key = 1;
?>

The example demonstrates how array_search() returns the first matching key for a given value and how the optional strict parameter can be used to enforce type‑safe comparisons.

backendPHPSearchphp-functionsarray-search
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.