Solved

How do you sum up an array?

Posted on 2011-02-15
5
339 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 109

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 109

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 109

Expert Comment

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

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Suggested Solutions

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

772 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