Solved

How do you sum up an array?

Posted on 2011-02-15
5
341 Views
Last Modified: 2012-05-11
I have an array that I would like to sum up i.e. I have the array $price[$j][4] and I would like all the results of that array added together and have a total. I hope that makes sense.
0
Comment
Question by:anotherdotcommer
  • 3
  • 2
5 Comments
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34899326
array_sum() maybe?  Please post a small test data set and I will show you how I would do it.
0
 

Author Comment

by:anotherdotcommer
ID: 34899381
Thanks Ray! Here is what I was trying. The page wouldn't load though.... <?php for ($j=0; $j<($price); $j++) {

echo ''.array_sum($price[$j][4]).''; }?>
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 34899408
Maybe something like this would work well for you.
<?php // RAY_temp_another.php
error_reporting(E_ALL);
echo "<pre>";

// TEST DATA
$arr[0][4] = 1;
$arr[1][4] = 2;
$arr[2][4] = 3;
$arr[3][4] = 4;

// ACTIVATE THIS TO SEE THE TEST DATA
// var_dump($arr);

// ADD IT ALL UP
$sum = 0;
$num = 0;
$max = count($arr);
while ($num < $max)
{
    $sum = $sum + $arr[$num][4];
    $num++;
}
echo $sum;

Open in new window

0
 

Author Comment

by:anotherdotcommer
ID: 34899510
It worked!! Thanks
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34899520
Glad to help!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question