Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work for loop increment value in PHP? [duplicate]

Tags:

php

I have checked for loop these two ways, but given same output:

1: Increment use ++$i

for($i=0; $i<10; ++$i){
    echo $i;
}

2: Increment use $i++

for($i=0; $i<10; $i++){
    echo $i;
}

These both code gave this output:

0 1 2 3 4 5 6 7 8 9

We learn ++$i mean pre increment, $i++ mean post increment,

why that post and pre increment not work? can someone please explain me? thank you.

like image 906
Mak Avatar asked Apr 20 '26 06:04

Mak


1 Answers

Value of $i++ and ++$i will be same after evaluation.

As $i++ first evaluate value of $i then increment $i.
And
++$i first increment then evaluate value of $i.

Here in for loop, it follows step
initialization
test condition(if true then execute body/else exit)
increment/decrement

As again its working for a new line, either you use $i++ or ++$i it will be the same.
But if you use it in between the for loop you can see the difference.
Check Link for more details

for example

$i++;  // Or ++$i;
echo $i;

It will give same value in both condition.
But if you use echo $i++; or echo ++$i then you will find difference.

like image 96
Himanshu Avatar answered Apr 21 '26 21:04

Himanshu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!