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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
