Reputation: 105
Take the following example of array manipulation with the Illuminate\Support\Collection class provided by the Laravel Framework.
$value = $arr->firstWhere('age', '>', 18);
$key = $arr->search($value, true);
In this code example, php must traverse the array twice. How can I prevent this from happening?
Upvotes: 1
Views: 2973
Reputation: 1708
You can pass a closure to the search
method.
$key = $arr->search(function ($item, $key) {
return $item['age'] > 18;
});
With arrow function (PHP >= 7.4.0)
$key = $arr->search(fn ($item, $key) => $item['age'] > 18);
https://laravel.com/docs/8.x/collections#method-search
Upvotes: 1