0

I use short if in PHP, and when Use this example

$a = 100 ? 200 : 300;

$a equal 200, but i don't know how below example work.

$a = 100 ?  : 300;

after this code $a equal 100.
Why?

aya
  • 1,597
  • 4
  • 29
  • 59
  • 1
    You've mistakenly set the value of `$a` to 100 instead of checking if it equals 100. `$a == 100 ? 200 : 300;` – Geoff Atkins Apr 20 '17 at 08:17
  • If this is a common mistake of yours, try using more Yoda conditions: `100 == $a`. If you had mistyped that as `100 = $a ? 200 : 300` that would have shown an error. – Kempeth Apr 20 '17 at 08:23

2 Answers2

2

In php manual: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise

tcPeng
  • 296
  • 1
  • 11
0

Let me explain so you can understand the differnece.

When you use one = it's assigning value, 
When you use == is checking if same value and 
When using === is checking value + type also.

So in your example $a = 100 ? 200 : 300; it is like this:

If $a can be set to 100 (which can) then True (so 200).

In your second example : $a = 100 ? : 300;

Again you are assinging $a to 100, which is true, so it remains 100 as your true condition is empty.

Simos Fasouliotis
  • 1,383
  • 2
  • 16
  • 35