0

I have a shop checkout function something like this:

    $min_delivery = 25;
    foreach ($shoppingCartItem as $item) {
     $insert->name = $item->name;
     $insert->price = $item->price;
     $insert->quantity = $item->qty;
     $insert->save();
     $total += $item->price*$item->qty;
    }

Is there any php function that would allow the foreach loop to happen only if ($total > $min_delivery) .

Or the only way would be to do the foreach twice, once only to calculate $total, then if ($total > $min_delivery) do a second foreach to insert into the database.

*EDIT - some details on why I want some other way instead of two loops:

The issue is that I can't trust the $item->price from the shopping cart because it comes from the user (and I don't verify it until checkout) so I need to check it against database before inserting.

So doing the loop twice would mean to query the database twice.

6
  • 2
    You answered your own question - first count total, then checkout. Commented Sep 5, 2018 at 15:55
  • @u_mulder That is one way yes, I asked if is there another way better? Commented Sep 5, 2018 at 15:56
  • You could use array_reduce to find the $total Commented Sep 5, 2018 at 15:57
  • Given that $total is calculated in the loop, I'm not sure that only executing the loop based on its value is going to get you very far. If there's a class involved that wraps the whole cart, adding a getTotal() method to it would make this a lot easier, and avoid the need to have a second dedicated loop. Commented Sep 5, 2018 at 15:57
  • 1
    Another method, would be to generate the total during add/remove, and keep it in the cart as a separate variable to directly look at when you need. But it creates variable maintenance during add/remove cart items. Commented Sep 5, 2018 at 15:59

1 Answer 1

0

Here's a possible solution

$total = array_reduce($shoppingCartItem,
    function($carry,$item) {
        return $carry + $item->price*$item->qty;
    }
);
$min_delivery = 25;
if ($total > $min_delivery) {
    ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

I added some details in the main question on why I am looking for a solution without two loops.
This is only one loop :). But if you don't trust $item->price, I think you should fix that in the $shoppingCartItem object before doing this calculation.
I tried to avoid doing a query every time a item is added to the cart. This way I only query the database once on the checkout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.