How does for loop works actually in php? - 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.

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 - sum array condition

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?

Echo issue, loops 4 times

I have this code
'$a = "pippo";
$b = "lucia";
for ($i=0;$i<strlen($a);$i++)
{
$c = "$a";
echo "$c";
}'
When I run it I see four times pippo instead of one time. Why does it happen?
Thanks in advance
It echos 'pippo' five times (pippopippopippopippopippo), because your loop says that it should. You start with $i = 0, the loop will continue while that is true. Every time your loop runs $i is incremented by 1. It will stop when the condition $i
Example:
$i = 0
$i = 1
$i = 2
$i = 3
$i = 4
$i = 5 (Will not execute loop, because condition $i<5 is not true anymore)

How do I square a number using a for loop in php?

My task, using php, is to create a random number, then make that number multiply itself. However i cannot use the multiply operator (*) and have been told to create a for loop instead however I'm having some troubles.
$startNum = rand(1,10);
for ($i = $startNum; $i <= 10; $i++)
{
echo $i;
}
This is what i have so far, however this is completely wrong and will only get a random number and count to 10 from it.
Any help would be very appreciated, thanks.
When squaring you are just multiplying a number by itself, another way to do this is through addition, add a number to itself x amount of times. So, with 4 squared, that is 4 * 4 or, 4 + 4 + 4 + 4.
Doing this in a for loop should be as simple as
$startNum = rand(1,10);
$endNum = 0;
for ($i = 0; $i < $startNum; $i++)
{
$endNum += $startNum;
}
echo $endNum;
Caveat: I don't program Php so forgive syntax errors.
$startNum*$startNum means that the loop should loop $startNum times and in each iteration add $startNum, i.e., the number itself
$s = 0;
for($i=1;$i<=$startNum;$i++){
$s += $startNum;
}
echo $s;
Still not using the multiplication operator :p
$n = mt_rand(1, 10);
echo array_sum(array_fill(0, $n, $n));
you can do this by simple addition(+) operator
square means add that number into same number for same time.
example : square of 2 means : 2+2;
square of 4 means : addition of 4 with 4 for 4 times : 4+4+4+4
so you can do like that
$startNum = rand(1,10);
$ans=0;
for ($i = 0 ;$i < $startNum; $i++)
{
echo $ans+=$startNum;
}

how to do this.. backwards?

I currently have:
$i = 1;
while {
echo $i;
$i++;
}
And it shows:
1
2
3
4 etc..
How would I make it display backwards?
For example
4
3
2
1 etc..
I basically want to do the exact same thing but flip it around.
$i = 10;
while($i>0) {
echo $i;
$i--;
}
Example - Print number through 0 to 5 with PHP For Loop
for($i=0; $i<=5; $i=$i+1)
{
echo $i." ";
}
In the above example, we set a counter variable $i to 0. In the second statement of our for loop, we set the condition value to our counter variable $i to 5, i.e. the loop will execute until $i reaches 5. In the third statement, we set $i to increment by 1.
The above code will output numbers through 0 to 5 as 0 1 2 3 4 5.
Note: The third increment statement can be set to increment by any number. In our above example, we can set $i to increment by 2, i.e., $i=$i+2. In this case the code will produce 0 2 4.
Example - Print number through 5 to 0 with PHP For Loop
What if we want to go backwards, that is, print number though 0 to 5 in reverse order? We simple initialize the counter variable $i to 5, set its condition to 0 and decrement $i by 1.
for($i=5; $i>=0; $i=$i-1)
{
echo $i." ";
}
The above code will output number from 5 to 0 as 5 4 3 2 1 0 looping backwards.
Good luck! :)
If you want to back-word sr number as per your count of rows in result then use this.
$num_rows = mysqli_num_rows($query);
$x = $num_rows;
$x--;
$i = 4;
while($i > 0) {
echo $i--;
}

Categories