Click here to Skip to main content
13,661,206 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

9K views
3 bookmarked
Posted 17 Sep 2014
Licenced CPOL

4 Pitfalls of PHP's Comparison Operators: When to Use == Versus ===

, 17 Sep 2014
Rate this:
Please Sign up or sign in to vote.
Tips for choosing between '==' (equals or loose comparison) and '===' (identical) operators in php.

Introduction

  • Equals or == for loose comparisons.
  • Identical or === for exact matches.

When choosing the correct operator you want to use in PHP, you will want to consider whether you want PHP to try different ways to match your data or if a more strict or exact match is needed. If your data is from a secure location or already validated, you may not need the strict identical === operator, but if your data is from an outside source (HTTP GET/POST or user entered), you may want to be more precise depending on the situation. Below are some example cases to keep in mind, starting with a look at the equals == operator.

1. Zero, false, empty strings, empty arrays, null are 'loosely' equal in PHP

Below are some base cases to keep in mind. The equals operator uses type juggling, and 0 can become false or an empty string.

Comparisons to Zero
0 == "" => True
"0" == false => True
"0" == 0 => True
0 == false => True

2. Watch out for string comparisons to 0 in PHP

Perhaps the strangest one is that any string with an equals comparison to 0 (as an integer) is True. If you always are expecting to compare both sides with a string, you should strongly consider using the identical operator '==='. Perhaps the strangest one is that any string with an equals comparison to 0.

String Comparisons
"str" == 0 => True (This one is definitely weird)
"str" == 1 => False
"str" == "0" => False
"strA" == "strB" => False

3. Type juggling converts strings to numbers and vice-versa

When using the equals operator, the strings are converted to a numeric value when the string comparison match fails.

Numeric Comparisons
3 == 4 => False
"3" == 3.0 => True
1 == "1" => True

4. Blank strings are 'loosely' evaluated null

This example shows that you need to be careful if there is a potential for blank strings to be passed along as data. Also, you may have expected that the string zero "0" would loosely evaluate to null since "0" loosely evaluated to false, but that is not the case.

Null Usage
"" == null => True
1 == null => False
null == null => True
null == 0 => True
null == "0" => False
null == false => True

The Identical Operator Removes the Loose Evaluations

The identical operator is great whenever you expect both sides of the comparison to have the same type and it will help keep you out of trouble. In this case, it helps remove the guesswork from the comparison and your output is more likely to match what you expect.

Comparisons to Zero
0 === "" => False
"0" === false => False
"0" === 0 => False
0 === false => False

String Comparisons
"str" === 0 => False
"str" === 1 => False
"str" === "0" => False
"strA" === "strB" => False

Numeric Comparisons
3 === 4 => False
"3" === 3.0 => False
1 === "1" => False

Null Usage
"" === null => False
1 === null => False
null === null => True
null === 0 => False
null === "0" => False
null === false => False

The Code

The PHP documentation for the comparison operators can be found here, and the chart that displays what the value of the comparisons should be is here.

Here is the sample code that generated the tests above:

echo "Comparisons to Zero<br />";
eval_string('0 == ""');
eval_string('"0" == false');
eval_string('"0" == 0');
eval_string('0 == false');
echo "<br />String Comparisons<br />";
eval_string('"str" == 0');
eval_string('"str" == 1');
eval_string('"str" == "0"');
eval_string('"strA" == "strB"');
echo "<br />Numeric Comparisons<br />";
eval_string('3 == 4');
eval_string('"3" == 3.0');
eval_string('1 == "1"');
echo "<br />Null Usage<br />";
eval_string('"" == null');
eval_string('1 == null');
eval_string('null == null');
eval_string('null == 0');
eval_string('null == "0"');
eval_string('null == false');

echo ("<br />Now Check as the === operator which removes type juggling:<br />");
echo "Comparisons to Zero<br />";
eval_string('0 === ""');
eval_string('"0" === false');
eval_string('"0" === 0');
eval_string('0 === false');
echo "<br />String Comparisons<br />";
eval_string('"str" === 0');
eval_string('"str" === 1');
eval_string('"str" === "0"');
eval_string('"strA" === "strB"');
echo "<br />Numeric Comparisons<br />";
eval_string('3 === 4');
eval_string('"3" === 3.0');
eval_string('1 === "1"');
echo "<br />Null Usage<br />";
eval_string('"" === null');
eval_string('1 === null');
eval_string('null === null');
eval_string('null === 0');
eval_string('null === "0"');
eval_string('null === false');

function eval_string($str) {
    $disp_str = str_pad($str,20," ");
    echo "$disp_str \t\t=> ".get_boolean_output(eval("return {$str};"))."<br />";
}

function get_boolean_output($val) {
    if ($val == false)
        return "False";
    else
        return "True";
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Right Handed Monkey
Chief Technology Officer WorxForUs
United States United States
I am a programmer who posts rambling on about java, Android, PHP, or whatever I am motivated to type on my charcoal colored Kinesis Freestyle2 keyboard. Please send +1's, shared links, warm thoughts of encouragement, or emasculating flames of internet fury to my blog. Thanks for reading!

righthandedmonkey.com

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMaybe not so weird Pin
SteveHit19-Sep-14 2:19
memberSteveHit19-Sep-14 2:19 
GeneralRe: Maybe not so weird Pin
antoinelacerte23-Sep-14 2:38
memberantoinelacerte23-Sep-14 2:38 
GeneralRe: Maybe not so weird Pin
Right Handed Monkey30-Oct-14 15:29
memberRight Handed Monkey30-Oct-14 15:29 
GeneralRe: Maybe not so weird Pin
Right Handed Monkey30-Oct-14 15:28
memberRight Handed Monkey30-Oct-14 15:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180810.1 | Last Updated 17 Sep 2014
Article Copyright 2014 by Right Handed Monkey
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid