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', ], ];
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'));
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))); }
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');
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!