Fatz
Fatz

Reputation:

Confusion over the value of a variable after running a PHP program

I'm studying for my finals and I came across this question:

consider this following PHP code, write the output after executing it

<?php
 $a=3;
 $b=$a++;
 IF($a>$b)
 {
   echo "a>$b";
 }
 else if ($a == $b)
 {
   echo "a=$b";
 }
 else
 {
   echo "a < $b";
 }
 ?>

When I output it in my text editor I get a < 3, but I don't understand why though?

I thought a is assigned to 3 and also b is assigned to a++ 3 and 3==3 so should a==3 be printed out?

Upvotes: 2

Views: 130

Answers (5)

Rakward
Rakward

Reputation: 1717

I tested your code and I get:

a>3

which makes sense

$a is 3 but is increased to 4 when you do $a++

$b is just $a before the ++ action so it stays 3

Think of $a++ as $a = $a + 1 then it makes sense

Upvotes: 1

Mohit Bumb
Mohit Bumb

Reputation: 2493

<?php
 $a=3;
 $b=$a++;
// $b = 3 and $a = 4 now
 IF($a>$b)
 {
   echo "a>$b";
 }
 else if ($a == $b)
 {
   echo "a=$b";
 }
 else
 {
   echo "a < $b";
 }
 ?>

Upvotes: 1

Martin Vrkljan
Martin Vrkljan

Reputation: 879

The $a++ incrementation happens after the expression gets evaluated, while ++$a would happen before.

So in your case, $b was first set to 3, and then $a was increased.

Upvotes: 2

hjpotter92
hjpotter92

Reputation: 80653

No, you are using post-increment operator on $a. So, $b will be assigned a value of 3, and later, when the statement is executed, $a will increment itself by one, and become 4. So, you'll now be comparing $a as 4 and $b as 3.

Hence you get the result a > 3

Upvotes: 5

dan-lee
dan-lee

Reputation: 14502

$a++ tells the variable $a explicitely to increase, no matter if you assigning to another variable or not! This gives the possibility to do things like if ($a++ > 10) { // ... in loops.

For your case you would have to take $b = $a + 1;

Upvotes: 1

Related Questions