++ plus plus won't add 1 in php

I am a PHP beginner. I created a php.php file in my WAMP environment and created the code:

<?php
$num = 10;
echo $num++;
?>

The problem is, only if I do $num + 1, I get 11. But If I do $num++ I still get 10 when refreshing the browser. Why is this? Thanks,

1 Like

What does this give you?

<?php
$num = 10;
$num++;
echo $num;
?>

How about


<?php
$num = 10;
echo ++$num;
?>

* hint , search for “Pre-increment” and “Post-increment”

1 Like

If you read http://php.net/manual/en/language.operators.increment.php you’ll see that the ++$num usage is called a "pre-increment, whereas $num++ is called “post-increment”. Post increment will increment the value after it is used for the expression. In this case, it is incremented after you echo it.

1 Like

Mittineague, In the first one - Xdebugger error. The second one did work… I did got 11… But I must say it’s very interesting to me to understand why for someone else it worked when I wrote it as I displayed in the original post…

So how would you explain post-increment worked for other people?..

The language wasn’t PHP?
The code was different than the example you posted?

Well, it is indeed PHP and the code was basically similar to mine, see here (time: 5:25):

I watched it, but I’d say it was more similar to my previous example

<?php
$num = 10;
$num++;
echo $num;
?>

that is the increment was a separate expression.

1 Like

Oh sorry, I missed this echo and mistakenly thought each one of the two was a call, maybe because in JS I putted it in the same place (at least in loops) and I confused it with the way it works in PHP - I guess the shortest way for me is to write it from before, i.e ++$num… This is the most minimal way I have in PHP.

2 Likes

I often have trouble with video tutorials. They tend to go faster than my eyes can see and brain can absorb.
A “4 minute” video can take me closer to 15 minutes what with all the pausing and rewinding.

Not to say they aren’t any good, many like learning from them. Just that I do better with something that I can move along at my own pace.

1 Like

It works the same way in both JavaScript and PHP.

<?php
$num = 10;
echo ++$num;
?>
var $num = 10
console.log(++$num);

with both like that the $num is incremented first and then displayed.

If you substitute $num++ for ++$num then it displays the value first and then increments it.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.