The difference between $i++ and ++$i in php

1. The usage of ++i (take a=++i, i=2 as an example) 
first add 1 to the value of i (that is, i=i+1 ), and then assign it to the variable a (that is, a=i ),
Then the final value of a is equal to 3, and the value of i is equal to 3.
So a=++i is equivalent to i=i+1,
the usage of a=i 2, i++ (take a=i++, i=2 as an example)
first assign the value of i to the variable a (that is, a=i), Then add 1 to the i value (that is, i=i+1 ),
then the final a value is equal to 2 and the i value is equal to 3 .
So a=i++ is equivalent to a=i , i=i+1
3, ++i and i++
a=++i is equivalent to i++ , a=i
a=i++ is equivalent to a=i , i++
4, ++i and When i++ is used alone, it is equivalent to i=i+1

If assigning to a new variable, ++i first increments the value of i by 1, and i++ first assigns i to the new variable.

5, imitation ($ i ++) + (++ $ i)

<?php 
  $i = 1;
  $a = $i++;
  echo 'a='.$a.'<hr />';
  echo 'i='.$i.'<hr />';
  $b = ++$i;
  echo 'b='.$b.'<hr />';
  echo $a+$b;
?>

Browser result:


6, imitation (++ $ i) + ($ i ++)
<?php 
  $i = 1;
  $a = ++$i;
  echo 'a='.$a.'<hr />';
  echo 'i='.$i.'<hr />';
  $b = $i++;
  echo 'b='.$b.'<hr />';
  echo $a+$b;
?>

Browser result:




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325908290&siteId=291194637