Home > Backend Development > PHP Tutorial > How to Find the Key for a Specific Value in a Multidimensional Array?

How to Find the Key for a Specific Value in a Multidimensional Array?

Mary-Kate Olsen
Release: 2024-12-11 05:57:13
Original
493 people have browsed it

How to Find the Key for a Specific Value in a Multidimensional Array?

Identifying Key for a Specific Array Value

When dealing with multidimensional arrays, it becomes necessary to search for specific values and retrieve the corresponding keys. In this scenario, we aim to find the key for a given value within a multidimensional array.

Array Search Using array_search()

One approach for searching arrays is to utilize the array_search() function, available in PHP versions 5.5.0 and above. This function requires two arguments: the target value and an array to search within. It returns the key associated with the target value if found, or FALSE otherwise.

Example

Consider the following multidimensional array:

$products = [
    1 => [
        'slug' => 'breville-one-touch-tea-maker-BTM800XL',
        'name' => 'The Breville One-Touch Tea Maker',
    ],
    2 => [
        'slug' => 'breville-variable-temperature-kettle-BKE820XL',
        'name' => 'Breville Variable-Temperature Kettle BKE820XL',
    ],
];
Copy after login

To search for the key associated with the slug breville-one-touch-tea-maker-BTM800XL:

$key = array_search('breville-one-touch-tea-maker-BTM800XL', array_column($products, 'slug'));
Copy after login

The array_column() function is used to extract the 'slug' values from each subarray into a one-dimensional array, enabling the array_search() function to perform the search efficiently.

Alternative Solution Using array_search_multidim()

For a self-contained solution, you can define a custom function like:

function array_search_multidim($array, $column, $key) {
    return (array_search($key, array_column($array, $column)));
}
Copy after login

This function allows you to pass the multidimensional array, the column name to search within (e.g., 'slug'), and the target value.

Example

$key = array_search_multidim($products, 'slug', 'breville-one-touch-tea-maker-BTM800XL');
Copy after login

The above is the detailed content of How to Find the Key for a Specific Value in a 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