Rohit Rohit - 6 months ago 31
PHP Question

How this is evaluated in PHP

While reading some questions on PHP. I read one question with it's answer as follows :

What will be the output of the code below and why?

$x = 5;
echo $x;
echo "<br />";
echo $x+++$x++;
echo "<br />";
echo $x;
echo "<br />";
echo $x---$x--;
echo "<br />";
echo $x;

Answer →
5
11
7
1
5


Here I am confused with $x+++ & $x--- & how its work & how exactly the expression $x+++$x++ evaluated. Can anybody please explain me about this. And also why just "echo $x+++" doesn't works & gives error.

Answer

this is concept of pre/post increment/decrement. that menas first if we go with post increment menas ($x++) what happen in this first it execute the expression which apply on that variable then it increment value by one for that variable like this below example.

 <?php
    $x = 5;
    echo $x++;
    echo "<br />";
    echo $x;
    ?>

OUTPUT

5

6

And second is pre increment in which what happen first it increment value for variable then execute expression which apply on that variable like below example.

<?php
    $x = 5;
    echo $x+++$x;
    echo "<br />";
    echo $x;
    ?>

OUTPUT

11

6

here in pre increment what happen first it adds (+1)in $x Then execute value for expression. same way pre/post decrement worksMore about increment/decrement

i hope this will help you.