Multidimensional array search by value in PHP
In this short article, we’ll talk about multidimensional array search by value in PHP. Here, you will see how to find the value from a multidimensional array and return the key using PHP.
Using the array_search() function, we will easily do this task. There are two parameters required in this function and the last one is optional. The first one is a value that we want to find in the array and the second one is an array. Let’s take an example for demonstration.
Example
In this example, we will have two arrays $employees
and $employeesData
. We will find the email of the employees from the $employeesData
array and create a new array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | $employees= [ [ "id" => "1", "firstname" => "John", "lastname" => "Garcia" ], [ "id" => "2", "firstname" => "Mike", "lastname" => "Brown" ], [ "id" => "3", "firstname" => "Daniel", "lastname" => "Williams" ], [ "id" => "4", "firstname" => "Maria", "lastname" => "Smith" ], ]; $employeesData = [ [ "emp_id" => "4", ], [ "emp_id" => "2", ], ]; |
Using the following syntax, we can find the key using the array_search()
function.
1 | array_search($value['id'], array_column($employeesData, 'emp_id')); |
Let’s use the following code to get the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php foreach($employees as $key => $value){ $index = array_search($value['id'], array_column($employeesData, 'emp_id')); $email = ($index!== false) ? $employeesData[$index]['email'] : ""; $employees[$key]['email'] = $email; } echo "<pre>"; print_r($employees); exit; ?> |
Output:
Run the above code and check the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | Array ( [0] => Array ( [id] => 1 [firstname] => John [lastname] => Garcia [email] => ) [1] => Array ( [id] => 2 [firstname] => Mike [lastname] => Brown [email] => mike@gmail.com ) [2] => Array ( [id] => 3 [firstname] => Daniel [lastname] => Williams [email] => ) [3] => Array ( [id] => 4 [firstname] => Maria [lastname] => Smith [email] => maria@gmail.com ) ) |
Reference article: Remove keys from an associative array in PHP
That’s it for today.
Thank you for reading. Happy Coding..!!