Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a collection contain another collection?

Using Laravel Collection, what the good way to check if check if a collection ($selectedItems) contain another collection ($orders)?

I am currently using two foreach loop $selectedItems and check if it exist in the $orders using another loop.

   $selectedItems = collect([
        ["ItemId" => "T123", "Price" => "12.00"],
        ["ItemId" => "T99", "Price" => "13.00"],
    ]);

    $orders = collect([
        ["ItemId" => "T123", "Cost" => "12.00"],
        ["ItemId" => "T99", "Cost" => "13.00"],
        ["ItemId" => "T33", "Cost" => "13.00"],
    ]);

    $found = [];

    foreach ($selectedItems as $selectedItem)
    {
        foreach($orders as $orderItem)
        {
            if ($orderItem['ItemId'] !== $selectedItem['ItemId']) {
                continue;
            }

            $found[] = $orderItem;
        }
    }


    if (count($found) == $selectedItems->count()) {
        dd("Matched");
    } else {
        dd("Not Matched");
    }

How to also ensure the Price from $selectedItems is the same as Cost in the $orders

like image 438
I'll-Be-Back Avatar asked Oct 21 '25 03:10

I'll-Be-Back


1 Answers

$selectedItems->diff($orders)->isEmpty();

This will diff the second collection from the first and if the result is empty you can be sure that all your items exist in the other collection.

like image 159
Aamir Avatar answered Oct 23 '25 19:10

Aamir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!