HDTuto.com

Multidimensional Array Search By Value in PHP



Are you looking for example of php multidimensional array search key by value. you'll learn how to search value in multidimensional array in php. it's simple example of how to search by key= value in a multidimensional array in php. if you want to see example of multidimensional array search by value in php then you are a right place.

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 - HDTuto.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...




July 8, 2020 | Category : PHP



Blog Search