Most efficient way to search for object in an array by a specific property's value
In PHP, you can use the built-in function array_filter()
to filter the array by a specific property's value. For example, if you have an array of objects and you want to find the object with a specific value for the "id" property, you can use the following code:
<?php
$array_of_objects = [(object) ['id' => 1, 'name' => 'John'], (object) ['id' => 2, 'name' => 'Jane'], (object) ['id' => 3, 'name' => 'Jim'], (object) ['id' => 4, 'name' => 'Jill']];
$specific_value = 2;
$filtered_array = array_filter($array_of_objects, function ($obj) use ($specific_value) {
return $obj->id == $specific_value;
});
print_r($filtered_array);
?>
Watch a video course
Learn object oriented PHP
Output:
Array ( [1] => stdClass Object ( [id] => 2 [name] => Jane ) )
The array_filter()
function filters the $array_of_objects
based on the condition specified in the anonymous function. In this case, the condition checks if the id
property of each object is equal to $specific_value
, which is 2
. Only the objects with id
equal to 2
will be included in the filtered array.
This is the most efficient way of searching for an object in an array by a specific property's value.