Jump to content
MakeWebGames

Increments


Jigsaw

Recommended Posts

Hi, im learning PHP atm and I'm very confused about how increments work and am failing to make sense of this example that was given to me:

e.g.

$a = 2; $b = $a++; // $a=3, $b=2

$a = 2; $b = ++$a; // $a=3, $b=3

So "$b" is simply in other terms "$a+1"?

And "$a" is 2, therefore $b is supposed to be 3 right? But it says its 2 instead?

Could explain how this works pls

 

Link to comment
Share on other sites

Thanks for the reply.

I get the idea that ++i will increase the value of whatever "i" may be and then return/show the new value of "i"

and i++ will increase the value of "i" but still keep the original value...

Could you please provide me with an example where this might be used in mccodes (just to strengthen my understanding)?

Link to comment
Share on other sites

I rarely come on here anymore...

 

<?php

$i = 1;         // Assign the value (int) 1 to the variable.
echo $i;        // Output the value of the variable.
echo PHP_EOL . PHP_EOL;

$i = 1;         // Assign the value (int) 1 to the variable.
echo $i + 1;    // Output the value of 1+1.
echo PHP_EOL . PHP_EOL;

$i = 1;         // Assign the value (int) 1 to the variable.
echo ++$i;      // Increment the variable by 1, then output.
echo PHP_EOL . PHP_EOL;

$i = 1;         // Assign the value (int) 1 to the variable.
echo $i++;      // Output the variable then increment by 1.

 

https://eval.in/708535

Notice how the last output is 1 (when I guess you expect it to be 2), this is because of where the operator (++) is. If you then output $i after this line, the output will be 2.

Edited by sniko
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...