Blum
Blum

Reputation: 899

Is there a way to get current order (place) of an element in a collection?

I mean this:

$collection = collect([['a' => 2], ['b' => 5], ['b' => 10]]);
$order = $collection->getOrderOf(['b' => 5]);
// $order should be 1 (if the first element is 0, second - 1, third - 2 and so on)

Is there something similar to this or I should make a collection extension?

Thanks

Upvotes: 1

Views: 96

Answers (3)

Jonathon
Jonathon

Reputation: 16293

The method you're looking for is search. This method accepts a value and returns a key that corresponds to it if it is in the collection. It returns false if the value could not be found.

$collection = collect([['a' => 2], ['b' => 5], ['c' => 10]]);
$collection->search(['a' => 2]); // 0
$collection->search(['b' => 5]); // 1
$collection->search(['c' => 10]); // 2
$collection->search(['c' => 11]); // false

I've just run the above code using Laravel Tinker (Version 5.5) and it seems to work without any issues.

Upvotes: 0

Sougata Bose
Sougata Bose

Reputation: 31749

This should work -

$collection = collect([['a' => 2], ['b' => 5], ['b' => 10]]);
$check = ['b' => 5];
$index = $collection->search(function ($value, $key) use($check) {
    // return key if key value pair matches
    return serialize($value) === serialize($check) ? $key : false; 
});
echo 'Found at - ' . $index;

Output

Found at - 1

Upvotes: 0

Sohel0415
Sohel0415

Reputation: 9853

This should work in your case:

$collection = collect([['a' => 2], ['b' => 5], ['b' => 10]]);
$pair_to_search = ['b' => 10];
$order =  $collection->values()->search(function ($item) use ($pair_to_search){
        $key = key($pair_to_search);
        foreach($item as $k => $v){
            if($k==$key && $v==$pair_to_search[$key])
                return $item;
        }
});
if($order)
{
       //you have index, do what you want
}

Upvotes: 1

Related Questions