Solved

How do you sum up an array?

Posted on 2011-02-15
5
337 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 108

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 108

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 108

Expert Comment

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

Featured Post

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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…

747 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now