PHP: Check for the Existence of A Key-Value Pair in a Multi-dimensional Array
In PHP 5.5.0 and above you no longer need a custom function to search through a multi-dimensional array. Combining the built-in PHP functions
array_column will extract the index of the inner array. Here’s the usage using meta variables:
$inner_array_index = array_search( $needle_value, array_column( $haystack_array, 'Key_holding_value' ) );
Example: Search a Multidimensional Array for a Value of a Specified Key
Here is our example: We are given an multidimensional array of consulting firms. Each inner row of the array includes columns such as the firm’s name, its location, and employee headcount.
Our challenge is to find the
array index (i.e., position) of the
consulting firm with a
location in Chicago.
$needle_value = 'Chicago' $haystack_array = $consulting_firms $key_holding_value = 'location'
The below will return “2” because “Chicago” is located at index 2 of the outer array.
$consulting_firms = array( array('name' => 'Bain & Co', 'location' => 'Boston', 'employees' => 2000), array('name' => 'Boston Consulting Group', 'location' => 'Boston', 'employees' => 700), array('name' => 'Mckinsey & Co', 'location' => 'Chicago', 'employees' => 3000), ); $inner_array_index = array_search( 'Chicago', array_column($consulting_firms, 'location') ); echo $inner_array_index; // 2
Credits: Hat tip to xfoxawy for posting this solution to PHP.net!
Don’t forget to enter your rants and raves in the comments section below!