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.
$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",
"email" => "[email protected]"
],
[
"emp_id" => "2",
"email" => "[email protected]"
],
];
Using the following syntax, we can find the key using the `array_search()` function.
array_search($value['id'], array_column($employeesData, 'emp_id'));
Let’s use the following code to get the output.
<!--?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;
?>
<h3 id="output:">Output:</h3>
<p>Run the above code and check the output.</p>
<pre>Array
(
[0] => Array
(
[id] => 1
[firstname] => John
[lastname] => Garcia
[email] =>
)
[1] => Array
(
[id] => 2
[firstname] => Mike
[lastname] => Brown
[email] => [email protected]
)
[2] => Array
(
[id] => 3
[firstname] => Daniel
[lastname] => Williams
[email] =>
)
[3] => Array
(
[id] => 4
[firstname] => Maria
[lastname] => Smith
[email] => [email protected]
)
)
</pre>
<p>Reference article: <a href="/remove-keys-from-an-associative-array-in-php" title="Remove keys from an associative array in PHP" target="_blank" rel="nofollow noopener noreferrer">Remove keys from an associative array in PHP</a></p>
<p>That’s it for today.<br>Thank you for reading. Happy Coding..!!</p>
<!-- /wp:html --></pre>