Unable to get Increment and Decrement operator to work

Hello every, I am trying to learn PHP I am going through the a php tutorial. I copied and paste an example program into TextPad.

Arithmetical Operators <?php $a = 42; $f = 10;
$c = $f++;
echo "Increment Operation Result: $c <br/>";
$c = $a--;
echo "Decrement Operation Result: $c <br/>";

?>

This will produce following result:

Increment Operation Result: 10
Decrement Operation Result: 42

I think the Result for $f should be 11 and for $a should be 41;

Am I missing anything?

[php]<?php
$a = 42;
$f = 10;
echo $a–;
echo ‘
’;
echo $a; // Returns $a, then decrements $a by one.
echo ‘
’;
echo $f++;
echo ‘
’;
echo $f; // Returns $f, then increments $f by one.[/php]

It’s working correctly but not the way you think it does. It returns the variable before increments/decrements occurs Here’s a link the explains it better: http://php.net/manual/en/language.operators.increment.php

Now if you want to do the way you think it would occur then just do --$a or ++$f ; however, in a for loop you would do it the first way $f++ (usually) :wink:

Thank You, It works fine now :D.

Wow … didnt know about this… Good to learn the diffrence between…

++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
–$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.

Sponsor our Newsletter | Privacy Policy | Terms of Service