Backend Development 4 min read

Using PHP's array_search() Function to Find Keys in an Array

This article explains PHP's array_search() function, detailing its prototype, parameters, return values, and provides clear code examples demonstrating how to locate element keys in associative arrays, including handling of strict type comparison and cases where the element is absent.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_search() Function to Find Keys in an Array

In PHP programming, it is often necessary to find the key name of a specific element in an array. PHP provides the array_search() function for this purpose. This article introduces the function’s usage and provides code examples.

Function Introduction:

The array_search() function searches an array for a given value and returns the corresponding key name. If multiple identical values exist, it returns only the first matching key.

Function Prototype:

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Parameter Description:

$needle : the value to search for.

$haystack : the array being searched.

$strict (optional): whether to use strict comparison (including type), default false.

Return Value:

If a matching value is found, the function returns its key name; otherwise it returns false .

Code examples:

$fruits = array(
    "apple"  => "苹果",
    "orange" => "橙子",
    "banana" => "香蕉",
    "grape"  => "葡萄"
);

$search_key = array_search("橙子", $fruits);
echo "橙子的键名是:" . $search_key; // Output: 橙子的键名是:orange

$search_key = array_search("柚子", $fruits);
if ($search_key === false) {
    echo "未找到匹配的值"; // Output: 未找到匹配的值
}

In the first example we search for the fruit “orange” and obtain the key orange . In the second example we look for a non‑existent element “柚子”; the function returns false and the conditional statement prints a not‑found message.

Notes:

When using array_search() , ensure that the type of the searched value matches the type of the array elements; otherwise a match will not be found even if the values appear equal. If the array contains multiple identical values, array_search() returns only the first key. To retrieve all matching keys, use array_keys() instead.

Summary:

The array_search() function is a handy tool in PHP for locating the key of a specific element within an array. Understanding its parameters and return behavior enables efficient array searching and improves coding productivity.

backendProgrammingphpphp-arrayarray-search
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.