tags:

views:

58

answers:

2

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.

+1  A: 

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
A: 

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