Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between $a==5 and 5==$a in php

Tags:

php

Today I have faced a question, I was unable to answer it, I have tried by making a php program but was unable to find out the exact reason for it if $a=5 then both($a==5 and 5==$a) are giving me output as boolean true and, if $a != 5 then both ($a==5 and 5==$a ) are giving me output as boolean false Can anyone tell me what is the difference between $a==5 and 5==$a from any language point of view.

**Program**
$a = 3;
var_dump( 5==$a );
var_dump( $a==5 );
$a = 5;
var_dump( 5==$a );
var_dump( $a==5 );


**Output**
boolean false

boolean false

boolean true

boolean true
like image 789
Ashish Avatar asked Mar 13 '23 13:03

Ashish


1 Answers

Comparisons like that are not affected by which value you write first. However, it is best practice to put the literal first, e.g. 5 == $x because if you mess up and only enter one equals sign, you'll get an error instead of an accidental value assignment, which is far easier to debug.

like image 72
Jacob See Avatar answered Mar 15 '23 05:03

Jacob See