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.
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:
Example of using the built-in function array_filter() to filter the array by a specific property's value in PHP
<?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);
?>
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
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.
Since array_filter() returns an array (preserving original keys), you can extract a single match using $result = reset($filtered_array); or array_values($filtered_array)[0] ?? null;. Always verify the result is not empty to avoid errors when the property value does not exist in the array.
Note: array_filter() iterates through the entire array. If you only need a single match, a foreach loop with an early break is faster. For repeated searches on the same dataset, consider building a lookup table (associative array) for O(1) access.