Prefix and Postfix Types in PHP
In fact, increment and decrement operations
can be written in two ways. In the postfix
form, the operation is written after the variable name,
like this: $a++
, and in the prefix
form - before the variable name, like this:
++$a
. Let's look at examples to see
the difference between the two methods.
In the following example, the first echo
will output
0
, because the output to the screen will happen first,
and only then the variable will increase:
<?php
$num = 0;
echo $num++; // will output 0, because the variable increases only after echo
echo $num; // will output 1 - the variable has changed
?>
And now the variable will increase first, and only then will the output to the screen occur:
<?php
$num = 0;
echo ++$num; // will output 1 - the variable increased immediately
?>
This behavior is true not only for output to the screen, but also for assignment:
<?php
$num1 = 0;
$num2 = $num1++; // the variable $num2 will be assigned 0
echo $num2; // will output 0
echo $num1; // will output 1 - the variable $num1 changed after being assigned to $num2
?>
Now let's change the postfix form to prefix:
<?php
$num1 = 0;
$num2 = ++$num1; // the variable $num2 will be assigned 1
echo $num2; // will output 1
?>
If our operation is performed on a separate line, then there is no difference between the prefix and postfix forms:
<?php
$num = 0;
++$num;
$num++;
echo $num; // will output 2
?>
Without running the code, determine what will be output to the screen:
<?php
$num = 3;
echo ++$num;
?>
Without running the code, determine what will be output to the screen:
<?php
$num = 3;
echo $num++;
?>
Without running the code, determine what will be output to the screen:
<?php
$num = 3;
echo --$num;
?>
Without running the code, determine what will be output to the screen:
<?php
$num = 3;
echo $num--;
?>
Without running the code, determine what will be output to the screen:
<?php
$num1 = 3;
$num2 = ++$num1;
echo $num1;
echo $num2;
?>
Without running the code, determine what will be output to the screen:
<?php
$num1 = 3;
$num2 = $num1++;
echo $num1;
echo $num2;
?>
Without running the code, determine what will be output to the screen:
<?php
$num1 = 3;
$num2 = --$num1;
echo $num1;
echo $num2;
?>
Without running the code, determine what will be output to the screen:
<?php
$num1 = 3;
$num2 = $num1--;
echo $num1;
echo $num2;
?>
Without running the code, determine what will be output to the screen:
<?php
$num1 = 3;
$num1++;
$num2 = $num1--;
echo $num1++;
echo --$num2;
?>