Jackson
Jackson

Reputation: 820

Add up numbers in a for each PHP?

I'm trying to add some numbers in a foreach loop in my PHP code. I am getting a percentage of numbers in a while loop in my MySQL query for each result that I get in my PHP page.

All I need to do is to add up the final values in and show them as total.

This is how I make up the percentage in my while loop in my MySQL query:

$percentage = 10;
$totalWidth = $fees;

$new_width = ($percentage / 100) * $totalWidth;

The $fees value is dynamic and it is different for each result in my while loop. the code above works as it should.

Now I want to add up all the values of $new_width. For example:

If one result's $new_width is 25 and the other one is 10 and another one is 5, I need to do this: $total = 25 + 10 + 5;

So I tried something like this:

$total = 0;

foreach($new_width as $var) {
   $total = $var + $var; 
}

echo $total;

but the above code doesn't really make sense and it won't do anything at all.

Could someone please advise on this matter?

Upvotes: 0

Views: 202

Answers (3)

Rudi Strydom
Rudi Strydom

Reputation: 4597

According to the logic, you are setting the total to 2 X $var.

My answer is very similar, but you add it to the total which is outside of the loop and the value will keep growing:

$total = 0;

foreach($new_width as $var) {
   $total += $var; 
}

echo $total;

Or simply as stated before, if it is the only value in the array:

$total = array_sum($new_width);

Upvotes: 0

Arjan
Arjan

Reputation: 9874

If you have an array of numbers and you want to calculate the sum of those numbers, you should use array_sum().

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

First you want to change this line in your while loop so you get an array:

$new_width = ($percentage / 100) * $totalWidth;

to this:

//Declare it as an array before your while loop
$new_width = array();
//In your while loop
$new_width[] = ($percentage / 100) * $totalWidth;
        //^^ See here

After this you just have to change the line in your foreach loop like this:

$total = $var + $var; 

to this:

$total += $var; 

(If you want you also can do this in your while loop)

Upvotes: 1

Related Questions