PHP: Array > Sum all the numeric elements? -


i found reference in php manual, interpretation pretty wrong:

$total = (sum ( array $_session['list'][$item]['price'] )); 

i want sum price of items in array session. please check screenshot: http://img684.imageshack.us/img684/6070/20110430010324.jpg

this code i'm using:

    <?php  session_start();  //getting list  $_session['list'] = isset($_session['list']) ? $_session['list'] : array();       //stock      $products = array(            'pineaple' => 500, 'banana' => 50, 'mango' => 150,             'milk' => 500, 'coffe' => 1200, 'butter' => 300,            'bread' => 450, 'juice' => 780, 'peanuts' => 800,            'yogurt' => 450, 'beer' => 550, 'wine' => 2500,      );         //saving stuff      $new_item = array(            'item' => $_post['product'],             'quantity' => $_post['quantity'],           'code' => $_post['code'],            'price' => $products[$_post['product']] * $_post['quantity'],       );    $new_product = true;     foreach($_session['list'] $key => $item) {           if ($item['item'] == $new_item['item']) {             $_session['list'][$key]['quantity'] += $new_item['quantity'];             $_session['list'][$key]['price'] = $products[$new_item['item']] * $new_item['quantity'];             $new_product = false;     }     }     if ($new_product) {           $_session['list'][] = $new_item;         }      //listing     echo  "<b>shopping list</b></br>";     foreach($_session['list'] $key => $item) {            echo 'product .'. $key. ' '. $item['item'], ' ', $item['quantity'], ' units: ', $item['price']. '<br />';         }   echo "</br> <a href='index.html'>return index</a> </br>";  //printing session var_dump($_session);  //session_destroy();  ?> 

$total = 0; foreach($_session['list'] $item) {   $total += $item['price']; } 

or if prefer functional style (php 5.3):

$total = array_reduce($_session['list'], function($a, $b) {   return $a['price'] + $b['price']; }); 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -