Difference between '==' (equal) and '===' (identical) comparison operators in PHP (with examples)
Two of the many comparison operators used by PHP are '==' (i.e. equal) and '===' (i.e. identical). The difference between the two is that '==' should be used to check if the values of the two operands are equal or not. On the other hand, '===' checks the values as well as the type of operands.
Let me explain more using some examples:
'==' (Equal):
if("22" == 22) echo "YES";
else echo "NO";
The code above will print "YES". The reason is that the values of the operands are equal. Whereas when we run the example code below:
'===' (Identical):
if("22" === 22) echo "YES";
else echo "NO";
The result we get is "NO". The reason is that although values of both operands are same their types are different, "22" (with quotes) is a string while 22 (w/o quotes) is an integer. But if we change the code above to the following:
if("22" === (string)22) echo "YES";
else echo "NO";
Then, the result will be "YES". Notice that 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.
In a nutshell, whenever you want to compare the values as well as the types of operands you'll use '===' otherwise you use '=='.
Please feel free to use the comments form below if you have any questions or need more explanation on anything. Use the icons below to share this tutorial with your friends.
tags cloud
popular searches
free download for mysql database server 5.1.5, php, linux, mysql mysql, mysql, java, install mysql, gearman, ubuntu, tools, source code, bison, mysql initialization, install cairo, laptop
Similar Tutorials:
- Simple Coding Style for PHP - Part 1/2
- PHP Useful functions (Part 2) - The currentURL function
- How to check PHP version number
- Generating Unique IDs in PHP
- Simple Coding Style for PHP - Part 2/2
Tutorials in 'Web Development > PHP' (more):
- Generating prime nos in PHP using multiprocessing - Geaman with PHP client Part I
- PHP Useful functions (Part 2) - The currentURL function
- PHP Useful functions (Part 1) - The inRange function
- Generating Unique IDs in PHP
- How to check PHP version number


Comments (write a comment):
0 comments so far. Be the first one to leave a comment on this article.