Search code examples
phplaravellaravel-5laravel-collection

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


Solution

  • What you want is the union collection function.

    It merges the collections and gives you a unique subset of results. Meaning that duplicates are removed. This way you don't have to check if one exists in the other, just that you have a collection with unique values.

    Read more about the union function here

    Edit: Because I misunderstood the intent of the original here is an answer that more correctly matches the intent.

    $found = [];
    $selectedItems->contains(function ($value, $key) use ($found){
        if($orders->contains($value)) {
            $found += [$key => $value]
        }
    })