Loop through an array of objects in PHP by other array values

✔ Recommended Answer

You can make use of php array filter function.

The main "trick" is to iterate over the all the cars and check if their corresporending ID is inside the selection. The array_filter() expects an array and a function. The function checks, if the current car ID is a part of the selection. When a filter function returns true, the value is kept, else it is dropped.

You could also go the other way around or use two nested foreach loops to create a new array, but this is just more easy.

Online Demo

$carsBySelection = array_filter($cars, function($car) use ($selection) {    return in_array($car["id"], $selection);});print_r($carsBySelection);
Array(    [0] => Array        (            [id] => 1            [name] => FORD        )    [2] => Array        (            [id] => 3            [name] => FIAT        )    [3] => Array        (            [id] => 4            [name] => RENAULT        ))

Source: stackoverflow.com

Answered By: Markus Zeller

Method #2

To loop through an array of objects in PHP by other array values, you can use a combination of array functions and loops.

Assuming you have an array of objects like this:

php
$people = [ ['name' => 'Alice', 'age' => 25], ['name' => 'Bob', 'age' => 30], ['name' => 'Charlie', 'age' => 35], ];

And another array of values like this:

php
$ages = [30, 35];

You can loop through the array of objects and filter it by the values in the other array like this:

php
foreach ($people as $person) { if (in_array($person['age'], $ages)) { // Do something with the person object echo $person['name'] . ' is ' . $person['age'] . ' years old.'; } }

In this example, the in_array() function checks if the age of each person in the $people array matches any of the ages in the $ages array. If it does, you can perform some action with that person object, such as printing their name and age.

Alternatively, you can also use the array_filter() function to create a new array that only contains the objects that match the criteria in the other array:

php
$filteredPeople = array_filter($people, function($person) use ($ages) { return in_array($person['age'], $ages); }); foreach ($filteredPeople as $person) { // Do something with the person object echo $person['name'] . ' is ' . $person['age'] . ' years old.'; }

In this example, the array_filter() function creates a new array containing only the objects that match the age criteria, and then you can loop through this new array to perform some action with each person object.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755