Hi Guys,
In one of the recent web developer interview, one interviewer ask “what is the difference etween == and === in php”. All are face this same situation in interview panel. Nobody knows the theory part. Then everybody shocked.
Based on this situation, I just describe what are the difference between these two. These are the comparison operators in PHP are = = (equal) and = = =(identical).
The = = operator just checks to see if the left and right values are equal. To check if the values of the two operands are equals or not.
‘ = = ‘ Example:
if(“111” == 111) echo “YES”;
else echo “NO”;
The values of the operands are equal, so the above code will print “YES”.
The = = = operator actually checks to see if the left and right values are equals. And also check to see if they are the same variable type like int or string etc. To check the values as well as the type of the operands.
‘= = =’ Example:
if(“111” === 111) echo “YES”;
else echo “NO”;
The values of both operands are same their types are different, “111” (with quotes) is a string while 111 (w/o quotes) is an integer. So the result we get is “NO”.
Change the above code as:
if(“111” === (string)111) echo “YES”;
else echo “NO”;
We changed the type of right operand to a string which is the same as the left operand (i.e. string). Now, the types and values of both left and right operands are the same hence both operands are identical. Then, the result will be “YES”.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.