PHP - Post & Pre Increment & Decrement

This is a quite shorter way to add 1 to or subtract 1  from a variable. 

Increment Operator
     "++" uses to increase 1

Decrement Operator
     "--" uses to decrease 1

     Ex:
        $no1 = 5;
        $no1++; // This is equal to $no1 = $no1 + 1;
        $no1--; // This is equal to $no1 = $no1 - 1;
  • There is a difference when the increment operator uses before the variable and after the variable. If the operator uses before the variable then the value get after increasing the variable value. But put the increment operator after the variable then 1st it print the variable value and then increase the value by 1.
         Ex:

         <?php
              $no1 = 5;
              echo $no1;  // This Prints 5
              echo $no1++;  // This also Prints 5,
              echo $no1;  // This Prints 6
              echo ++$no1;  // This Prints 7

              echo $no1;  // This Prints 7
              echo $no1--;  // This also Prints 7,

              echo $no1;  // This Prints 6
              echo --$no1;  // This Prints 5

        ?>

No comments:

Post a Comment