PHP - sum array condition - php

I want to sum all data from inside a foreach loop and compare this to values in an outer foreach using jquery, but I don't know how to sum all of the data points from my inner foreach.
Here is the view:
<?php
$a = array(5,15,25);
$sum = 0;
foreach($a as $b) {
$sum += $b;
if($sum < 30) {
echo "<br>" . $sum;
}
}
?>
my answer: 5 20
expectation : 20 25

I see that you are a new contributor so welcome to Stack Overflow :)
Let's take a look at your code. You are executing the line echo "<br>" . $sum; at every iteration of the foreach loop.
Let's try to analyse the loop, iteration after iteration.
Iteration 1 (element 5):
Add 5 to $sum -> $sum = 5.
Is $sum smaller than 30? Yes! -> print <br> 5.
Iteration 2 (element 15):
Add 15 to $sum -> $sum = 20.
Is $sum smaller than 30? Yes! -> print <br> 20.
Iteration 3 (element 25):
Add 25 to $sum -> $sum = 45.
Is $sum smaller than 30? No -> nothing to print.
This is basically what your code is doing. Remember that, at the end of every iteration, you add the current array value to $sum. The starting value for $sum is 0 so at the end of each iteration you'll have:
$sum = 5 (0 + 5)
$sum = 20 (5 + 15)
$sum = 45 (20 + 25)
As you can see the output is correct. Why are you expecting to get 20 25?

Related

WHY for loop php output this result?

I don't understand for loop in PHP,
`$total = 0;
for ($i = 1; $i <= 10; $i++) {
$total += $i;
}
echo $total;`
normally equal an 11 no ? he output me 55, but for python when you execute similar code with "while loop"
total = 0
while total <= 10:
total+=1
print(total)
output me 11
please someone can help me?
Your PHP and python code is not equivalent. In python you just add 1 each time in the loop. However in the PHP you are adding the value to the $i value, which of course keeps increasing every time - i.e. 1+2+3+3+5...etc.
You could write
$total += 1;
or just
$total++;
instead and it would work the same as the python. But then again that makes $total redundant because it just has the same value as $i, and you don't really need two variables doing the same job.
Or you could write a while loop to be more directly equivalent to the python:
$total = 0;
while ($total <=10) {
$total++;
}
echo $total;
PHP CODE
In the PHP code, you get the sum of 1 to 10 numbers using for loop.
That is,
0+1+2+3+4+5+6+7+8+9+10 = 55
Because you have initially given 0 to the $total variable in the PHP code. Then you have given 1 to the $i variable in the for loop and you keep increasing the loop 1 by 1 until the value in $i is less than 10 or equal 10. Then the value in $i is added to the value in the $total.
1st Iteration
$total = total + 1
2nd Iteration
$total = total + 2
3rd Iteration
$total = total + 3
.
.
.
.
.
10th Iteration(because $i <= 10)
$total = total + 10
Then exit the loop and now $total = 55
PYTHON CODE
In the python code you have also using while loop and 0 is assigned to the total variable at the beginning of the code.
In this case all you have to do is increase the value of the total variable by 1
That is,
1st Iteration
total = total + 1
2nd Iteration
total = total + 1
3rd Iteration
total = total + 1
.
.
.
.
.
10th Iteration(because total <= 10)
total = total + 1
Then exit the while loop and now total = 11
These two codes are not the same!!!
Simply because in php code you are incrementing it with i as:total+i
if total wore intially zero 0+1+2+3+4+5+6+7+8+9+10==55
while in python you are incrementing it with total+1 not i
so each time only +1 incrementaion
so 0+1+1+1+1+1+1+1+1+1+1=11

(PHP) Why does this generator-script adds the starting value + the step-value to the starting value?

the title may be pretty confusing. Here's a script which requires a start-end and step value to add numbers to the start value:
function addieren($start, $ende, $schritt = 1) {
if ($start < $ende) {
$erg = 0;
for ($i = $start; $i <= $ende; $i += $schritt) {
$erg += $i;
yield $erg;
}
}
}
foreach (addieren(2, 10, 2) as $erg) {
echo $erg . "<br>";
}
So the start value is 2, the end value is 10 (but it's not ending at 10 as the result shows), and it should add 2 to the $i every step.
Here's the output:
2
6
12
20
30
The first output is clear to me, since the $erg was 0 and it added the 2 because of 2 steps.
But the next output is 6 and I don't get why. In the second loop, $i is 2 and and the script says: $i += $schritt so when $i is 2 and the $schritt value is also 2, why doesn't that output 4 as the second output? Hope you get what I mean.. I guess it's a pure logic error in my head.

How does for loop works actually in php?

I'm a newbie to php and I've understood all other loops in php but the question is I cannot understand how the for loops works for ex:
Here is the code;
$a = 0;
$b = 0;
for ($i=0; $i < 5; $i++) {
$a += 10;
$b += 5;
}
echo("At the end of the loop a=$a and b=$b");
When I execute this script the value of a = 50 and b = 25!
Is it multiplying the a value with i's increment value? like 10 * 5 = 50.
You start with $i=0, then you do $a+10 and $b+5 as long as $i <5
$i=0, $a=10, $b=5
$i=1, $a=20, $b=10
$i=2, $a=30, $b=15
$i=3, $a=40, $b=20
$i=4, $a=50, $b=25
$i=5, now the loop stops because $i is no longer <5
Your loop runs five times. Each time through the loop you add 10 to the value of $a. Doing that five times gives you 50.
This is the way it works.
Let's say you have a no dollars. And I tell you that I will give you a dollar everytime you do 5 chores. However, I will only give you 5 dollars. At first you have no dollars and after one chore I give you 5 dollars. Now you have 5 dollars. You do another chore and I give you another 5, bringing you to ten. I have now given you two dollars. I give you another 5 - you have 15. I give you another - 20 - and one more; bringing you to 25 dollars. Now I have given you my limit of dollars, and our loop is complete.
In this story, my dollars are your $i value. Beginning at 0, working up to 5. Your chores are your $b values, which are added to every time.
Code example:
for ($dollars=0; $dollars < 5; $dollars++) {
$chores += 5;
}
+= is not increment its an assignment operator.
http://php.net/manual/en/language.operators.assignment.php
As I mentioned in the comments, and others in their answers. += will add the value to on the right to the value on the left. so in a loop its like this
step 0 $a = 5 ( 0+5)
step 1 $a = 10 (5[previous iteration exit value]+5 )
step 2 $a = 15 (10[previous iteration exit value] + 5)
so on....
Of note is you can also do -= *= etc. and .=or append all the same kind of operation.
The for statement is used when you know how many times you want to execute a statement or a block of statements.
Syntax:
for (initialization; condition; increment){
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables on each pass of the loop −
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i = 0; $i<5; $i++ ) {
$a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
</body>
</html>
This will produce the following result −
At the end of the loop a = 50 and b = 25
For loop is entry condition loop. It evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet
The statements inside this for loop block will run 5 times, the value of $i will be 0 to 4;
Imagine the loops are running separately.
$a=0;
$b=0;
for ($i = 0; $i < 5; $i++){
echo $a += 10;
echo '<br>';
}
And the output like this.
10
20
30
40
50
Now another Loop
for ($i=0; $i < 5; $i++) {
echo $b += 5;
echo '<br>';
}
And the output like this
5
10
15
20
25
In each iteration it adds 10 and 5 to previous number of iteration using the assignment operator x += y.

Decoding function to better understand

I am revisiting PHP and want to relearn where i lack and i found one problem, i am unable to understand the following code, where as it should output 6 according to the quiz, i got it from but i broke it down to simple pieces and commented out to better understand, according to me the value of $sum should be 4, but what i am doing wrong, maybe my breakdown is wrong?
$numbers = array(1,2,3,4);
$total = count($numbers);
//$total = 4
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
//0+1 = 1
//0+2 = 2
//0+3 = 3
//0+4 = 4
if ($i < $total) {
$sum = $sum + $number;
//1st time loop = 0 < 4 false
//2nd time loop = 0 < 1 false
//3rd time loop = 0 < 2 false
//5th time loop = 0 < 3 false
//6th time loop = 4 = 4 true
//$sum + $number
//0 + 4
//4
}
}
echo $sum;
This is very basic question and might get down vote but it is also a strong backbone for people who want to become PHP developer.
You don't understand the last part in the loop. It actually goes like this now:
if($i < $total) {
$sum = $sum + $number;
//1st time loop: $sum is 0. $sum + 1 = 1. $sum is now 1.
//2nd time loop: $sum is 1. $sum + 2 = 3. $sum is now 3.
//3rd time loop: $sum is 3. $sum + 3 = 6. $sum is now 6.
//4th time loop: it doesn't get here. $i (4) < $total (4)
//This is false, so it doesn't execute this block.
}
echo $sum; // Output: 6
I altered your script a little so that it will print out what it's doing as it goes. I find it useful to do this kind of thing if I'm having a hard time thinking through a problem.
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$i = 0;
$j = 0;
foreach($numbers as $number) {
$i = $i + 1;
echo "Iteration $j: \$i +1 is $i, \$sum is $sum, \$number is $number";
if ($i < $total) {
$sum = $sum + $number;
echo ", \$i is less than \$total ($total), so \$sum + \$number is: $sum";
} else {
echo ", \$i is not less than \$total ($total), so \$sum will not be increased.";
}
echo '<br>'; // or a new line if it's CLI
$j++;
}
echo $sum;
Lets Explain
Your initial value of $i is 0 but when you start looping you increment it by 1, so the start value of $i is 1.
When checking the condition you did't use equal sign to check for the last value whether you start value is 1. So its clear that your loop must be run for 1 less of total.
$i = 0;
foreach($numbers as $number) {
$i += 1;
if ($i < $total)
$sum += $number;
}
echo $sum;
Analysis
Step: 1 / 4
The value of $number is: 1 And The value of $i is: 1
Step: 2 / 4
The value of $number is: 2 And The value of $i is: 2
Step: 3 / 4
The value of $number is: 3 And The value of $i is: 3
When the loop again go for a check the value of $i increased by 1 and at 4. So trying to match the condition if ($i < $total), where the value of $i and $total is equal, so it will return false. So the loop only run for 3 time.
Result
6

Basic PHP clarification for variables on how executed/saved

I have the follow:
$sum = 10 + 10;
is the above line executed saved to $sum as 20 to use it from now on
or if everytime i echo $sum, it will run the 10+10?
It only calculates it once to set the value of $sum.
So from then on out $sum is equal to 20.
So the 10+10 is only calculated the first time.
During the lifetime of the script the value of 10 + 10 will be assigned to the $sum variable - no further 10 + 10 will be calculated when using $sum.
PHP is not inherently lazy nor it has lazy primitives, so value assignation is executed immediately. To simulate some sort of lazy functionality you can declare a function:
funciton sumTen() {
return 10 + 10;
}
sumTen() // will calculate the value every time.
$sum = 0;
echo $sum; // will print 0
$sum = 10 + 10;
echo $sum; // will print 20
$sum = 5;
echo $sum; // will print 5

Categories