1

Increment and decrement operators in PHP

Well, here it is another important thigs that actually I didn’t know until some days ago and it is nor only the increment and decrement operators, but the fact that according to the position of these, we can determine the order how the value will increase or decrease. I will give a pair of examples latter but first let me introduce you (in case you don´t remember) what are these operators.

  • $sample++ - This is the “Post-increment” operator. It returns the current value of
    the variable and increases it by 1.
  • $sample— - Programmers refer to this operator as “Post-decrement.” Basically, this
    operator gives the current value of a variable before decreasing it by 1.
  • $++sample – This operator, which is called “Pre-increment,” increases the value of
    the variable it is attached to and returns the resulting value.
  • $—sample – With this operator, you can decrease the value of an operand by one
    before retrieving an output.

Here the important point is that according with the position of these operators we can determine if the original value will be displayed or not, for example, I created a for iteration in a php script embedded in a html file and I will give you a kind of demostration of how we can actually put in practice what I just mentioned. So, the code is the following

<html>
        <head>
                <title>This is a sample</title>
        </head>
        <body>

                <?php
                        $x = 10;

                        for($i = 0; $i < 10; $i++){
                                echo $x--."\n\t\t";
                        }
                ?>

        </body>
</html>

And the output is the next:

<html><head><title>This is a sample</title></head><body>

                10
                9
                8
                7
                6
                5
                4
                3
                2
                1

        </body></html>

But we can change the code and code the following

<html>
        <head>
                <title>This is a sample</title>
        </head>
        <body>

                <?php
                        $x = 10;

                        for($i = 0; $i < 10; $i++){
                                echo --$x."\n\t\t";
                        }
                ?>

        </body>
</html>

And we must pay atention in the order of the numbers, which is the main purpose of this article

<html><head><title>This is a sample</title></head><body>

                9
                8
                7
                6
                5
                4
                3
                2
                1
                0

        </body></html>
Escribe tu comentario
+ 2