Faqts : Computers : Programming : Languages : PHP : Common Problems : Arrays

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

23 of 26 people (88%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How do i add the values(which are prices) in an array?

Nov 13th, 2000 16:37
Ben Udall, Jaime Kozlowski,


If the price is just a number (i.e. 5.50), then you can just loop 
through the array and add them.  However, if there's a something like a 
dollar sign in the price (i.e. $4.25), you'll have to extract the 
number, before adding.
This sample function will account for both possibilities by simply 
stripping any character that doesn't make-up a number from the
array value.  Not fool-proof, but should work for most cases.
function array_sum( $array ) {
    $total = 0;
    foreach ($array as $value)
        $total += ereg_replace("[^0-9.-]+", "", $value);
    return $total;
}