-1

The $_SESSION has the following data array.

Array (
[totalprice] => 954
[cart] => Array (
      [115] => Array (
      [name] => MÅNESKINN
      [price] => 268.00
      [count] => 1 )
[80] => Array (
      [name] => DELFINLEK  
      [price] => 268.00
      [count] => 1 )
[68] => Array (
      [name] => OPPDAGELSEN
      [price] => 418.00
      [count] => 1 ) )
[shipping] => 65 ) 

Now I need to compare the price and find the highest price in order to determine the shipping charge with the following code.

...
$shippingprice = 25.0;    
if ( $priceincart > 268 ){
   $shippingprice = 65.0;
}
...
$_SESSION['shipping'] = $shippingprice;

How can I find the highest price from the array?

Thanks in advance.

shin
  • 31,901
  • 69
  • 184
  • 271
  • You calculate the shipping charge upon the most expensive item? – Gumbo Jan 10 '10 at 14:32
  • Why are you re-posting the same problem? The solution is effectively the same as in: http://stackoverflow.com/questions/2037241/how-to-pull-out-data-from-session-in-php – John Parker Jan 10 '10 at 14:37
  • I am asking question step by step. What's wrong with it? – shin Jan 10 '10 at 14:43
  • @Gumbo It most expensive thing is the largest size. – shin Jan 10 '10 at 14:44
  • 2
    If you learnt anything from the previous answer, you'd know the answer to this. – John Parker Jan 10 '10 at 14:52
  • I learnt but I did not know how to proceed next. – shin Jan 10 '10 at 17:41
  • Why don’t you calculate the shipping costs upon the total weight/volume of all items? That would be more accurate than just assuming that the most expensive item is also the largest. (Recently I ordered a special pencil of about $10 but the package was so huge it could hold 200 of them. Maybe a similar algorithms was responsible for that too.) – Gumbo Jan 10 '10 at 17:48

2 Answers2

1

Try this simple algorithm:

$max = 0;
foreach ($_SESSION['cart'] as $item) {
    if ($item['price'] > $max) {
        $max = $item['price'];
    }
}

It iterates the cart items and tests if the item’s price is larger than the current maximum and updates the maximum if it’s larger.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

This should work, although it assumes a PHP version >= 5.3.

$max_price = array_reduce($array['cart'], function($acc, $in) { 
    return max($acc, $in['price']); 
}, 0) or $max_price = 0;

Given a starting smallest price (0 zero), array_reduce will call the callback function at each element of $array['cart'] (where each element is also an array), and then the called in function will return the maximum of $acc or $in['price']. This maximum value will then be passed in to the callback function (as $acc) the next time it is called.

In the event that array_reduce() returns NULL, $max_price is set to zero.

Peter Goodman
  • 438
  • 3
  • 12