PHP Multidimensional Array Search By Value Example

By Hardik Savani May 14, 2024 Category : PHP

Are you looking for example of multidimensional array search by value in php. Here you will learn php multidimensional array search by value. I’m going to show you about php multidimensional array search key by value. We will look at example of how to search value in multidimensional array in php. Let's get started with how to search by key= value in a multidimensional array in php.

If you need to get find value from multidimensional array in php. you can search key value in multidimensional array in php.

Here, i will give you simple array what is requirement and how i will solve that problem. right now i have two array $students and $studentsAddress in this example. when i display $students array with foreach loop i also need to display address on those student address too. But problem is there is a user_id key with first array id and some records. so i used array_column() and array_column() array function to solve.

Let's see full example so you can understand what i mean:

Solution:

array_search($value['id'], array_column($studentsAddress, 'user_id'))

Example:

<?php

$students = [

[

"id" => "1",

"name" => "Hardik",

"email" => "hardik@gmail.com"

],

[

"id" => "2",

"name" => "Vimal",

"email" => "vimal@gmail.com"

],

[

"id" => "3",

"name" => "Harshad",

"email" => "harshad@gmail.com"

],

[

"id" => "4",

"name" => "Harsukh",

"email" => "harsukh@gmail.com"

]

];

$studentsAddress = [

[

"user_id" => "3",

"address" => "Rajkot, Gujatat, India"

],

[

"user_id" => "1",

"address" => "Surat, Gujatat, India"

]

];

?>

<h1>PHP Multidimensional Array Search By Value Example - ItSolutionStuff.com</h1>

<table border="1" width="700">

<tr>

<td>ID</td>

<td>Name</td>

<td>Email</td>

<td>Address</td>

</tr>

<?php foreach ($students as $key => $value): ?>

<tr>

<td><?php echo $value['id'] ?></td>

<td><?php echo $value['name'] ?></td>

<td><?php echo $value['email'] ?></td>

<td>

<?php

$key = array_search($value['id'], array_column($studentsAddress, 'user_id'));

if (!empty($key) || $key === 0) {

echo $studentsAddress[$key]['address'];

}

?>

</td>

</tr>

<?php endforeach ?>

</table>

Now you can see bellow preview:

I hope it can help you...

Tags :
Shares