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
Release: 2025-01-04 01:06:39
Original
976 people have browsed it

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;
}
Copy after login

Method 2: Using array_search with array_column (PHP 5.5.0 and above)

$key = array_search('100', array_column($userdb, 'uid'));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template