Master PHP’s array_search: Find Keys Quickly and Accurately

This tutorial explains how PHP's array_search() function locates the key of a specific value in an array, details its parameters and return values, and provides clear code examples illustrating both successful searches and handling of missing elements.

php Courses
php Courses
php Courses
Master PHP’s array_search: Find Keys Quickly and Accurately

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

Function Overview

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 ] )

Parameters

$needle

: the value to search for. $haystack: the array to be searched. $strict (optional): whether to use strict comparison (type and value). Default is false.

Return Value

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

Code Examples

Below are examples using array_search():

$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: 未找到匹配的值
}

Notes

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

Conclusion

The array_search() function is a practical tool in PHP for locating the key of a specific element in an array, helping you search efficiently and improve coding productivity.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPProgramming tutorialphp-functionsarray manipulationarray_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

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.