Home >Backend Development >PHP Tutorial >How Can I Efficiently Search for a Value and Retrieve Its Key in a PHP Multidimensional Array?

How Can I Efficiently Search for a Value and Retrieve Its Key in a PHP Multidimensional Array?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 01:06:39959browse

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:

    • $key = search_by_uid('100', $userdb);
  • Method 2:

    • $key = array_search('100', array_column($userdb, 'uid'));

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn