Home >Backend Development >PHP Tutorial >How Can I Efficiently Search for a Value and Retrieve Its Key in a PHP Multidimensional Array?
PHP Multidimensional Array Search by Value
Problem:
Given a multidimensional array, how can you efficiently search for a specific value (e.g., a user ID) and retrieve its corresponding array key?
Solution:
Below are two approaches to search for a value in a multidimensional array and obtain its key:
Method 1: Using Loops
function search_by_uid($id, $array) { foreach ($array as $key => $val) { if ($val['uid'] === $id) { return $key; } } return null; }
Method 2: Using array_search with array_column (PHP 5.5.0 and above)
$key = array_search('100', array_column($userdb, 'uid'));
Calling the Functions:
To use these functions:
Method 1:
Method 2:
The $key variable will contain the array key of the found value (or null if not found).
The above is the detailed content of How Can I Efficiently Search for a Value and Retrieve Its Key in a PHP Multidimensional Array?. For more information, please follow other related articles on the PHP Chinese website!