How to search for a collection item with a key?

I have the following collection:

$this->items = collect([$productId => [
                    'name' => $product->title,
                    'price' => $product->price,
                    'is_sale' => $product->is_sale,
                    'sale_price' => $product->sale_price,
                    'sale_percent' => $product->sale_percent,
                    'can_use_promocode' => $product->can_use_promocode,
                    'qty' => 1,
                ]);
]);

How to search for an item with a key? In the documentation ( https://laravel.com/docs/5.2/collections ) I do not see any methods for this

UPD: For example, a user added an item to the cart ( $this->items). I want to check the availability of an item in the basket (I need to do this with the key). Analog for php function array_key_exists, but for collections.

+4
source share
2 answers

use has ()

if($this->items->has('key_name_to_check')){
    ///your task if exists
}
+2
source

You can do it:

$this->items->toArray()[$key]

Or you can use the method first():

$this->items->first(function($i, $k) use($key) {
    return $key === $k;
});

Update

, , offsetExists().

offsetExists() array_key_exists(), , , :

return array_key_exists($key, $this->items);
+1

Source: https://habr.com/ru/post/1692460/


All Articles