PHP 7.0.26 Released

Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
$a != $b Not equal TRUE if $a is not equal to $b after type juggling.
$a <> $b Not equal TRUE if $a is not equal to $b after type juggling.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.
$a <=> $b Spaceship An integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b. Available as of PHP 7.

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

<?php
var_dump
(== "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true

switch ("a") {
case 
0:
    echo 
"0";
    break;
case 
"a"// never reached because "a" is already matched with 0
    
echo "a";
    break;
}
?>
<?php  
// Integers
echo <=> 1// 0
echo <=> 2// -1
echo <=> 1// 1
 
// Floats
echo 1.5 <=> 1.5// 0
echo 1.5 <=> 2.5// -1
echo 2.5 <=> 1.5// 1
 
// Strings
echo "a" <=> "a"// 0
echo "a" <=> "b"// -1
echo "b" <=> "a"// 1
 
echo "a" <=> "aa"// -1
echo "zz" <=> "aa"// 1
 
// Arrays
echo [] <=> []; // 0
echo [123] <=> [123]; // 0
echo [123] <=> []; // 1
echo [123] <=> [121]; // 1
echo [123] <=> [124]; // -1
 
// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo 
$a <=> $b// 0
 
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "c"]; 
echo 
$a <=> $b// -1
 
$a = (object) ["a" => "c"]; 
$b = (object) ["a" => "b"]; 
echo 
$a <=> $b// 1
 
// only values are compared
$a = (object) ["a" => "b"]; 
$b = (object) ["b" => "b"]; 
echo 
$a <=> $b// 1

?>

For various types, comparison is done according to the following table (in order).

Comparison with Various Types
Type of Operand 1 Type of Operand 2 Result
null or string string Convert NULL to "", numerical or lexical comparison
bool or null anything Convert both sides to bool, FALSE < TRUE
object object Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation
string, resource or number string, resource or number Translate strings and resources to numbers, usual math
array array Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)
object anything object is always greater
array anything array is always greater

Example #1 Boolean/null comparison

<?php
// Bool and null are compared as bool always
var_dump(== TRUE);  // TRUE - same as (bool)1 == TRUE
var_dump(== FALSE); // TRUE - same as (bool)0 == FALSE
var_dump(100 TRUE); // FALSE - same as (bool)100 < TRUE
var_dump(-10 FALSE);// FALSE - same as (bool)-10 < FALSE
var_dump(min(-100, -10NULL10100)); // NULL - (bool)NULL < (bool)-100 is FALSE < TRUE
?>

Example #2 Transcription of standard array comparison

<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1$op2)
{
    if (
count($op1) < count($op2)) {
        return -
1// $op1 < $op2
    
} elseif (count($op1) > count($op2)) {
        return 
1// $op1 > $op2
    
}
    foreach (
$op1 as $key => $val) {
        if (!
array_key_exists($key$op2)) {
            return 
null// uncomparable
        
} elseif ($val $op2[$key]) {
            return -
1;
        } elseif (
$val $op2[$key]) {
            return 
1;
        }
    }
    return 
0// $op1 == $op2
}
?>

See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.

Warning

Comparison of floating point numbers

Because of the way floats are represented internally, you should not test two floats for equality.

See the documentation for float for more information.

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Example #3 Assigning a default value

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    
$action 'default';
} else {
    
$action $_POST['action'];
}

?>
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

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.

Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.

Note:

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Example #4 Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true 'true' false) ? 't' 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

Null Coalescing Operator

Further exists the "??" (or null coalescing) operator, available as of PHP 7.

Example #5 Assigning a default value

<?php
// Example usage for: Null Coalesce Operator
$action $_POST['action'] ?? 'default';

// The above is identical to this if/else statement
if (isset($_POST['action'])) {
    
$action $_POST['action'];
} else {
    
$action 'default';
}

?>
The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise.

In particular, this operator does not emit a notice if the left-hand side value does not exist, just like isset(). This is especially useful on array keys.

Note: Please note that the null coalescing operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; in a return-by-reference function will therefore not work and a warning is issued.

Note:

Please note that the null coalescing operator allows for simple nesting:

Example #6 Nesting null coalescing operator

<?php

$foo 
null;
$bar null;
$baz 1;
$qux 2;

echo 
$foo ?? $bar ?? $baz ?? $qux// outputs 1

?>

add a note add a note

User Contributed Notes 53 notes

up
91
crazy888s at hotmail dot com
7 years ago
I couldn't find much info on stacking the new ternary operator, so I ran some tests:

<?php
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 1 ?: 0 ?: 3 ?: 2; //1
echo 2 ?: 1 ?: 0 ?: 3; //2
echo 3 ?: 2 ?: 1 ?: 0; //3

echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ?: 0 ?: 2 ?: 3; //2
echo 0 ?: 0 ?: 0 ?: 3; //3
?>

It works just as expected, returning the first non-false value within a group of expressions.
up
37
Harry Willis
3 years ago
I was interested about the following two uses of the ternary operator (PHP >= 5.3) for using a "default" value if a variable is not set or evaluates to false:

<?php
(isset($some_variable) && $some_variable) ? $some_variable : 'default_value';

$some_variable ?: 'default_value';
?>

The second is more readable, but will throw an ERR_NOTICE is $some_variable is not set. Of course, this could be overcome by suppressing the notice using the @ operator.

Performance-wise, though, comparing 1 million iterations of the three statements

  (isset($foo) && $foo) ? $foo : ''
  ($foo) ?: ''
  (@$foo) ?: ''

results in the following:

  $foo is NOT SET.
    [isset] 0.18222403526306
    [?:]    0.57496404647827
    [@ ?:]  0.64780592918396
  $foo is NULL.
    [isset] 0.17995285987854
    [?:]    0.15304207801819
    [@ ?:]  0.20394206047058
  $foo is FALSE.
    [isset] 0.19388508796692
    [?:]    0.15359902381897
    [@ ?:]  0.20741701126099
  $foo is TRUE.
    [isset] 0.17265486717224
    [?:]    0.11773896217346
    [@ ?:]  0.16193103790283

In other words, using the long-form ternary operator with isset($some_variable) is preferable overall if $some_variable may not be set.

(error_reporting was set to zero for the benchmark, to avoid printing a million notices...)
up
58
arnaud at arnapou dot net
7 years ago
[Editor's note: consider using ===]

I discover after 10 years of PHP development something awfull : even if you make a string comparison (both are strings), strings are tested like integers and leading "space" character (even \n, \r, \t) is ignored ....

I spent hours because of leading \n in a string ... it hurts my developper sensibility to see two strings beeing compared like integers and not like strings ... I use strcmp now for string comparison ... so stupid ...

Test code :
<?php

test
("1234", "1234");
test("1234", " 1234");
test("1234", "\n1234");
test("1234", "1234 ");
test("1234", "1234\n");

function
test($v1, $v2) {
    echo
"<h1>[".show_cr($v1)."] vs [".show_cr($v2)."]</h1>";
    echo
my_var_dump($v1)."<br />";
    echo
my_var_dump($v2)."<br />";
    if(
$v1 == $v2) {
        echo
"EQUAL !";
    }
    else {
        echo
"DIFFERENT !";
    }
}

function
show_cr($var) {
    return
str_replace("\n", "\\n", $var);
}

function
my_var_dump($var) {
   
ob_start();
   
var_dump($var);
   
$dump = show_cr(trim(ob_get_contents()));
   
ob_end_clean();
    return
$dump;
}

?>

Displays this ->

[1234] vs [1234]
string(4) "1234"
string(4) "1234"
EQUAL !

[1234] vs [ 1234]
string(4) "1234"
string(5) " 1234"
EQUAL !

[1234] vs [\n1234]
string(4) "1234"
string(5) "\n1234"
EQUAL !

[1234] vs [1234 ]
string(4) "1234"
string(5) "1234 "
DIFFERENT !

[1234] vs [1234\n]
string(4) "1234"
string(5) "1234\n"
DIFFERENT !
up
25
thomas dot oldbury at tgohome dot com
10 years ago
Be careful when using the ternary operator!

The following will not evaluate to the expected result:

<?php
echo "a string that has a " . (true) ? 'true' : 'false' . " condition in. ";
?>

Will print true.

Instead, use this:

<?php
echo "a string that has a " . ((true) ? 'true' : 'false') . " condition in. ";
?>

This will evaluate to the expected result: "a string that has a true condition in. "

I hope this helps.
up
25
jwhiting at hampshire dot edu
13 years ago
note: the behavior below is documented in the appendix K about type comparisons, but since it is somewhat buried i thought i should raise it here for people since it threw me for a loop until i figured it out completely.

just to clarify a tricky point about the == comparison operator when dealing with strings and numbers:

('some string' == 0) returns TRUE

however, ('123' == 0) returns FALSE

also note that ((int) 'some string') returns 0

and ((int) '123') returns 123

the behavior makes senes but you must be careful when comparing strings to numbers, e.g. when you're comparing a request variable which you expect to be numeric. its easy to fall into the trap of:

if ($_GET['myvar']==0) dosomething();

as this will dosomething() even when $_GET['myvar'] is 'some string' and clearly not the value 0

i was getting lazy with my types since php vars are so flexible, so be warned to pay attention to the details...
up
25
mail at mkharitonov dot net
3 years ago
Be careful with the "==" operator when both operands are strings:
<?php
var_dump
('123' == '       123'); // true
var_dump('1e3' == '1000'); // true
var_dump('+74951112233' == '74951112233'); // true
var_dump('00000020' == '0000000000000000020'); // true
var_dump('0X1D' == '29E0'); // true
var_dump('0xafebac' == '11529132'); // true
var_dump('0xafebac' == '0XAFEBAC'); // true
var_dump('0xeb' == '+235e-0'); // true
var_dump('0.235' == '+.235'); // true
var_dump('0.2e-10' == '2.0E-11'); // true
var_dump('61529519452809720693702583126814' == '61529519452809720000000000000000'); // true in php < 5.4.4
up
40
Anonymous
12 years ago
The following contrasts the trinary operator associativity in PHP and Java.  The first test would work as expected in Java (evaluates left-to-right, associates right-to-left, like if stmnt), the second in PHP (evaluates and associates left-to-right)

<?php

echo "\n\n######----------- trinary operator associativity\n\n";

function
trinaryTest($foo){

   
$bar    = $foo > 20
           
? "greater than 20"
           
: $foo > 10
               
? "greater than 10"
               
: $foo > 5
                   
? "greater than 5"
                   
: "not worthy of consideration";   
    echo
$foo." =>  ".$bar."\n";
}

echo
"----trinaryTest\n\n";
trinaryTest(21);
trinaryTest(11);
trinaryTest(6);
trinaryTest(4);

function
trinaryTestParens($foo){
   
   
$bar    = $foo > 20
           
? "greater than 20"
           
: ($foo > 10
               
? "greater than 10"
               
: ($foo > 5
                   
? "greater than 5"
                   
: "not worthy of consideration"));   
    echo
$foo." =>  ".$bar."\n";
}

echo
"----trinaryTestParens\n\n";
trinaryTestParens(21);
trinaryTestParens(11);
trinaryTest(6);
trinaryTestParens(4);

?>

Output:

######----------- trinary operator associativity

----trinaryTest

21 =>  greater than 5
11 =>  greater than 5
6 =>  greater than 5
4 =>  not worthy of consideration

----trinaryTestParens

21 =>  greater than 20
11 =>  greater than 10
6 =>  greater than 5
4 =>  not worthy of consideration
up
19
rshawiii at yahoo dot com
11 years ago
You can't just compare two arrays with the === operator
like you would think to find out if they are equal or not.  This is more complicated when you have multi-dimensional arrays.  Here is a recursive comparison function.

<?php
/**
* Compares two arrays to see if they contain the same values.  Returns TRUE or FALSE.
* usefull for determining if a record or block of data was modified (perhaps by user input)
* prior to setting a "date_last_updated" or skipping updating the db in the case of no change.
*
* @param array $a1
* @param array $a2
* @return boolean
*/
function array_compare_recursive($a1, $a2)
{
   if (!(
is_array($a1) and (is_array($a2)))) { return FALSE;}   
   
   if (!
count($a1) == count($a2))
      {
       return
FALSE; // arrays don't have same number of entries
     
}
     
   foreach (
$a1 as $key => $val)
   {
       if (!
array_key_exists($key, $a2))
           {return
FALSE; // uncomparable array keys don't match
             
}
       elseif (
is_array($val) and is_array($a2[$key]))  // if both entries are arrays then compare recursive
          
{if (!array_compare_recursive($val,$a2[$key])) return FALSE;
           }
       elseif (!(
$val === $a2[$key])) // compare entries must be of same type.
          
{return FALSE;
           }
   }
   return
TRUE; // $a1 === $a2
}
?>
up
11
Jeremy Swinborne
5 years ago
Beware of the consequences of comparing strings to numbers.  You can disprove the laws of the universe.

echo ('X' == 0 && 'X' == true && 0 == false) ? 'true == false' : 'sanity prevails';

This will output 'true == false'.  This stems from the use of the UNIX function strtod() to convert strings to numbers before comparing.  Since 'X' or any other string without a number in it converts to 0 when compared to a number, 0 == 0 && 'X' == true && 0 == false
up
16
Anonymous
8 years ago
Note: The ternary shortcut currently seems to be of no use in dealing with unexisting keys in an array, as PHP will throw an error. Take the following example.

<?php
$_POST
['Unexisting'] = $_POST['Unexisting'] ?: false;
?>

PHP will throw an error that the "Unexisting" key does not exist. The @ operator does not work here to suppress this error.
up
18
fernandoleal at dragoncs dot com
10 years ago
If you need nested ifs on I var its important to group the if so it works.
Example:
<?php
//Dont Works
//Parse error: parse error, unexpected ':'
$var='<option value="1" '.$status == "1" ? 'selected="selected"' :''.'>Value 1</option>';
//Works:
$var='<option value="1" '.($status == "1" ? 'selected="selected"' :'').'>Value 1</option>';

echo
$var;
?>
up
13
bimal at sanjaal dot com
4 years ago
I came across peculiar outputs while I was attempting to debug a script

<?php
# Setup platform (pre conditions somewhere in a loop)
$index=1;
$tally = array();

# May work with warnings that $tally[$index] is not initialized
# Notice: Undefined offset: 1 in D:\htdocs\colors\ColorCompare\i.php on line #__
# It is an old fashioned way.
# $tally[$index] = $tally[$index] + 1;

# Does not work: Loops to attempt to change $index and values are aways unaffected
$tally[$index] = isset($tally[$index])?$tally[$index]:0+1;
$tally[$index] = isset($tally[$index])?$tally[$index]:0+1;
$tally[$index] = isset($tally[$index])?$tally[$index]:0+1;
/*
# These three lines output:
Array
(
    [1] => 1
)
*/

# Works: This is what I need/expect
# $tally[$index] = 1+(isset($tally[$index])?$tally[$index]:0);

print_r($tally);
?>

The second block obviously does not work what one expects.
Third part is good.
up
11
bishop
11 years ago
When you want to know if two arrays contain the same values, regardless of the values' order, you cannot use "==" or "===".  In other words:

<?php
(array(1,2) == array(2,1)) === false;
?>

To answer that question, use:

<?php
function array_equal($a, $b) {
    return (
is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a));
}
?>

A related, but more strict problem, is if you need to ensure that two arrays contain the same key=>value pairs, regardless of the order of the pairs.  In that case, use:

<?php
function array_identical($a, $b) {
    return (
is_array($a) && is_array($b) && array_diff_assoc($a, $b) === array_diff_assoc($b, $a));
}
?>

Example:
<?php
$a
= array (2, 1);
$b = array (1, 2);
// true === array_equal($a, $b);
// false === array_identical($a, $b);

$a = array ('a' => 2, 'b' => 1);
$b = array ('b' => 1, 'a' => 2);
// true === array_identical($a, $b)
// true === array_equal($a, $b)
?>

(See also the solution "rshawiii at yahoo dot com" posted)
up
12
Hayley Watson
10 years ago
Note that the "ternary operator" is better described as the "conditional operator". The former name merely notes that it has three arguments without saying anything about what it does. Needless to say, if PHP picked up any more ternary operators, this will be a problem.

"Conditional Operator" is actually descriptive of the semantics, and is the name historically given to it in, e.g., C.
up
12
Cuong Huy To
6 years ago
In the table "Comparison with Various Types", please move the last line about "Object" to be above the line about "Array", since Object is considered to be greater than Array (tested on 5.3.3)

(Please remove my "Anonymous" post of the same content before. You could check IP to see that I forgot to type my name)
up
13
gondo
3 years ago
beware of the fact, that there is no `<==` nor `>==` therefore `false <= 0` will be `true`. php v. 5.4.27
up
11
alan dot g at nospam dot net
7 years ago
a function to help settings default values, it returns its own first non-empty argument :

make your own eor combos !

<?php

/*
* Either Or
*
* usage:  $foo = eor(test1(),test2(),"default");
* usage:  $foo = eor($_GET['foo'], foogen(), $foo, "bar");
*/

function eor() {
   
$vars = func_get_args();
     while (!empty(
$vars) && empty($defval))   
        
$defval = array_shift($vars);         
     return
$defval;
}



?>
up
15
stepheneliotdewey at gmail [period] com
10 years ago
Note that typecasting will NOT prevent the default behavior for converting two numeric strings to numbers when comparing them.

e.g.:

<?php
if ((string) '0123' == (string) '123')
    print
'equals';
else
    print
'doesn\'t equal';
?>

Still prints 'equals'

As far as I can tell the only way to avoid this is to use the identity comparison operators (=== and !==).
up
16
adam at caucho dot com
11 years ago
Note: according to the spec, PHP's comparison operators are not transitive.  For example, the following are all true in PHP5:

"11" < "a" < 2 < "11"

As a result, the outcome of sorting an array depends on the order the elements appear in the pre-sort array.  The following code will dump out two arrays with *different* orderings:

<?php
$a
= array(2,    "a""11", 2);
$b = array(2,    "11", "a"2);
sort($a);
var_dump($a);
sort($b);
var_dump($b);
?>

This is not a bug report -- given the spec on this documentation page, what PHP does is "correct".  But that may not be what was intended...
up
11
kapoor_rajiv at hotmail dot com
8 years ago
A quick way to do mysql bit comparison in php is to use the special character it stores . e.g
<?php
                                       
if ($AvailableRequests['OngoingService'] == '')
                                            echo
'<td>Yes</td>';
                                        else
                                            echo
'<td>No</td>';

?>
up
8
jeronimo at DELETE_THIS dot transartmedia dot com
13 years ago
For converted Perl programmers: use strict comparison operators (===, !==) in place of string comparison operators (eq, ne). Don't use the simple equality operators (==, !=), because ($a == $b) will return TRUE in many situations where ($a eq $b) would return FALSE.

For instance...
"mary" == "fred" is FALSE, but
"+010" == "10.0" is TRUE (!)

In the following examples, none of the strings being compared are identical, but because PHP *can* evaluate them as numbers, it does so, and therefore finds them equal...

<?php

echo ("007" == "7" ? "EQUAL" : "not equal");
// Prints: EQUAL

// Surrounding the strings with single quotes (') instead of double
// quotes (") to ensure the contents aren't evaluated, and forcing
// string types has no effect.
echo ( (string)'0001' == (string)'+1.' ? "EQUAL" : "not equal");
// Prints: EQUAL

// Including non-digit characters (like leading spaces, "e", the plus
// or minus sign, period, ...) can still result in this behavior, if
// a string happens to be valid scientific notation.
echo ('  131e-2' == '001.3100' ? "EQUAL" : "not equal");
// Prints: EQUAL

?>

If you're comparing passwords (or anything else for which "near" precision isn't good enough) this confusion could be detrimental. Stick with strict comparisons...

<?php

// Same examples as above, using === instead of ==

echo ("007" === "7" ? "EQUAL" : "not equal");
// Prints: not equal

echo ( (string)'0001' === (string)'+1.' ? "EQUAL" : "not equal");
// Prints: not equal

echo ('  131e-2' === '001.3100' ? "EQUAL" : "not equal");
// Prints: not equal

?>
up
12
user@example
13 years ago
With Nested ternary Operators you have to set the logical  parentheses to get the correct result.

<?php
$test
=true;
$test2=true;

(
$test) ? "TEST1 true" :  ($test2) ? "TEST2 true" : "false";
?>
This will output: TEST2 true;

correct:

<?php
$test
=true;
$test2=true;

(
$test) ? "TEST1 true" : (($test2) ? "TEST2 true" : "false");
?>

Anyway don't nest them to much....!!
up
9
hiroh2k at yahoo dot com
13 years ago
if you want to use the ?: operator, you should be careful with the precedence.

Here's an example of the priority of operators:

<?php
echo 'Hello, ' . isset($i) ? 'my friend: ' . $username . ', how are you doing?' : 'my guest, ' . $guestusername . ', please register';
?>

This make "'Hello, ' . isset($i)" the sentence to evaluate. So, if you think to mix more sentences with the ?: operator, please use always parentheses to force the proper evaluation of the sentence.

<?php
echo 'Hello, ' . (isset($i) ? 'my friend: ' . $username . ', how are you doing?' : 'my guest, ' . $guestusername . ', please register');
?>

for general rule, if you mix ?: with other sentences, always close it with parentheses.
up
10
Alex
11 years ago
I think everybody should read carefully what "jeronimo at DELETE_THIS dot transartmedia dot com" wrote. It's a great pitfall even for seasoned programmers and should be looked upon with a great attention.
For example, comparing passwords with == may result in a very large security hole.

I would add some more to it:

The workaround is to use strcmp() or ===.

Note on ===:

While the php documentation says that, basically,
($a===$b)  is the same as  ($a==$b && gettype($a) == gettype($b)),
this is not true.

The difference between == and === is that === never does any type conversion. So, while, according to documentation, ("+0.1" === ".1") should reassa href, we6t1.".1"ng the strn == as, it retassa), true is actu, it retore `f( for wpart isd !==).
up
13
3 years ago
mane end is roundingmore ternary opemples 'ncar-coalesd fo'rnary ope:t onr1u mi onr2,erely== is onr1uparen't evall the osent!==).
up
7 13
6 years ago
When1"ngs rounding,mpledecimalesult.

<?phpvar_dump();
var_dump();
var_dump(== );
?>
< the s(9) "590217,73"br />
In loatbjectthe way>// a st so, ann>// a s-eing comtical,ding the sbjectthe way> loatb so, ann> loat-eing com.br />
< waeing comple the strs to usn'tmbos !

<?phpvar_dump(();
var_dump(();
var_dump((] == ();
?>
< the s(9) "590217,73"br /> < the s(9) "590217,73"br />
up
16
3 years ago
ncarbr />   &n- sql bor cos6t1.".ring toftrict compar way>booleancmp( two numring? ml"> In the t> Inautena po wasd dump ote tway>boolean.nbsp;hingions wIhould ote tway> two numringt!==).
up
8
6 years ago
<?php
t;/td>'($i) ? : ; ; t;/td>'($i) ? : );
?>
<" is [baNested te]ALSE.

thiref, we6dingmore teren't evas iult"2">t;/td.(b is )is is(b is )i- ee alsoend= may res.0" is!==).
up
12
3 years ago
=1, 2 ord">=0, 3 ord">=1]>?><$B = [1 ord">=1, 3 ord">=0, 2 ord">=1]>?><;?phpvar($mlt; 2 $Bord">);&n//0" is!?phpvar($Blt; 2 $Aord">);&n//0" is!?php<;?phpvar($mltg 2 $Bord">);&n//0" is!?phpvar($Bltg 2 $Aord">);&n//0" is!?php<;?php * EiClt; 2 Dt;==`Dlt; 2 C ( so, can sC != D)ende===:
<$C = [1 ord">=1, 2 ord">=1, 3 ord">=0]>?><$D = [1 ord">=1, 3 ord">=1, 2 ord">=0]>?><;?phpvar($Clt; 2 $D)&n//0" is t?phpvar($Dlt; 2 $C)&n//0" is t?php<;?phpvar($Cltg 2 $D)&n//0" is t?phpvar($Dltg 2 $C)&n//0" is t?php<;?phpvar($De ($aC)&n//0" is t==).
up
13
6 years ago
?><;?php< may rn ===:

6 e'srror: syntax'srror,nunexne eed T_UNSET?><;?php"Conditi TheeoftIF thEis >Thehis rmalesult.
}}<;?php< may rn ===:
un. (s lt"3 pemc be gHer sueeoftlt"1+lt"2 evenlt"3r />}<;?php

up
16
saspambogachdewey at gjaal dot com
7 years ago
<?php
function funtion function (((else
  &nswitchord">(
else
    &ncaseord">(
(] == else
      &nthrow,new>] ==
();
    &ncaseord">(
== else
      &nthrow,new>] ==
();
    &ncaseord">(
(] == else
      &nthrow,new>] ==
();
    &nqual"
);
    &nqual"
else
      &nqual"
true);
t==).
up
13
8 years ago
"otcaltpari br />s an exaan ume=== is af the fn't eewhatkned" so, abe wen1"ngohe d sorttass=o get hasentencedimp ote the fn't e. Ifs ha the fn't eewhat is actukned",eret the defn't eeThis b larresult.
?>ord">=(: ((t==).Male?>ord">=(: ((t==).Female?>?>
rd">(rd">((// SurrounHTMLowing. Ifss rounvng?' rd">((rd">(echo rd">((t==).
up
4 12
Anywt tht goh2y at gjaal dot com
3 years ago
<$a ord">= a)>?><$a['foo'] or'oof'>?>
<$b or@nbsp['foo'] ?: 'Nses o')>?><$c or@nbsp['bar'] ?: 'Nsebar')>?><;?phpvar($b, $c)>?><;?php. (t!==).
up
5 13
6 years ago
var(0+010"sta$gues");';?php<-tg 2 , it ret" is!?php<;?php// a strisay> tws nral,dingbeginna su?><;?php<<c-r 'ult">var(0+010"2sta$gues");';?php<-tg 2 , it ret" is t?php<;?php
up
12
8 years ago
When we6ding tws nr0. ===.
if you wanThis a disve ">funcence betaudingore `fn't eeakara booleanc not Yor,h ==re o=wish wanThis a disve ">funcence betaubooleancore `fakara zero true.

funcelse> iesult.

<?php: ;(: ;(: ;
(
((<{nbsp; echo ;
(
== (== (== <{nbsp; echo ;
(
== (== (== <{nbsp; echo ;td">;
In the folln ===:;
In irhe wo cases, ua1 so,$bn1"ngto==idecompassan. So, ,$c thito==idecompore `. Ifst in waion i get a `mple> * Eioftding irhe wo cth>"Conditar />I w you bsp;omp"Tnot " ===.
Inlthe a `mpI's owl=== lyn weo, an ||&nary opem wademo==rrumy== is t1.".ua1 so,$bndoints: an* evaluotassa nces with are iternary ope,t;==`ever $c can* evaluotore ` true.

up
12
6 years ago
6, thtnthtnthe tANDu the fHeuat= uexamwef you wan the f true.
6fully Thiss wo oftdinmp; is the.nbsp;; issn't 9">td === is wes...) aefully />snot 1 so,ully />nts: not . br />For examlete. aefuew you a Stuare snot 1elset in any ritybje eesult.

<?php;;;&br />&n* fromo or e a stords dinm.else
&br />&n*/else
&nqual"
(;
&npsm" eed bd">(
;

&npublic ord">function
(
&n{else
&nbr />&nqual"
t==).      &nbr />&nqual"t==).(&br />&nqual";

&nqual"
funcrsnoirrHere' ===asentoftdhat Stuare < soelse
&br />&n* the en't evas wo p; sg E=== is wes eosur __co==rruc>().else
&br />&n*/else
&nqual"
function
&n{else
&nbr />  re">: ((
t==).] == t==).;
&n}rd">;

&nbublic ord">function

&n{else
&nbr />  requal"
t==).;
&n}rd">;

&nbublic ord">function

&n{else
&nbr />  requal"
t==).;
&n}rd">;

&nbublic ord">function

&n{else
&nbr />  requal"
. t==).&nbr />&nqual". t==).. ;
&n}rd">;<}rd">;td">;() ord">functtheHeuat=lt"ithe snaing toauseprimitiv snWE WANTn. So, ,alsoenot s(Stuare fun,crsnoirrHere'argo doctoftdhat Stuare <--e for weliminevas ing e Neelsere'IDENTITY '==='sculd ANDuprfalltr doeswith odata.ring tfromoasse sbjn. Oneswith o"userintticeb">',alsoenot s() ord">func the en't evas lsoustuare _id, diialahe fHeelsetwwa//uare snain you ; is the tuser--e for wound ass=" possibty hole.

Her".1"rt>s an exa--e e'l gja sql br/>coctuANDutrck wascrew sqlupmbos !

<?php;(;] == : (((] == : (((echo . ;echo . ;;<# Culd eelseenot iter; isCORRECT s, ende===:">: ((t==).) ? : &nqual";;<# Culd eelseenot iterby HACKING>; iskned" n't eeoftustuare _idende===:">: ((t==).) ? : &nqual";td">;al,din />Hernyr anytw
up
12
7 years ago
cognized as> two nual' the strn ==1"ngto=r coed swap; sg E=. Ifstorstrck"abc"+010" abc",,cteThis bsp; reb is a/>s ne eed. To avoio, an any type conves, sin eyn we6ding are iternary opem(===d !==).
up
12
6 years ago
tis lseemptern't ee waynmphmore tiv :e===:
<$n't ee= $ppagA ?: $ppagBr;?php<$n't ee= $ppagA lse$n't ee= ppagBr;==).
up
12

<?php<$n't1e-2' : ) ? : ;td">;
<?php<$n't1e-2' : : ;t==).
up
0 12
neldagjaalorgt com
= === is doints: you ; is the asss:e===:
<- Cuntrarck wa ing o gHer as o("E an exa#2 T> nscrip>funcoft==asdard d">= t sst compai), sqldogHe* o * bsp; re tis iftdin left-hn ==1">= t snthtnHer"asss >al,din,right-hn ==1">= tever s i.br /><- Bef, we6ofst in,luat= may redepy depvending"keese> i doi get sst compabjn.e===:

For ex:e===:

<?php<$a1e-2' =sset((=sset((=sset((=sset(;(=sset((=sset((=sset((=sset(;;(var$test=sset(    &nbr />&nqual";var$test=sset(    &nbr />&nqual"t==).
up
0 12
6years ago
* Eibooleancord ; sg Ei sncss=nevad sway>// a s:br />
<?php
&nqual"
. ) ? : () ? : t==).
up
- 12
= ==cd">y ; is the in The oent fall iftdinyn1"ngtbspnnually dihe dre ,aso Imc be gd />In the foll ord">fun. Huagfully diial />usgful swasomebody.;?php;a dihe dre approachdth.s "rshawiiiroh2k at yahoo do"1risa akenesult.

<?phpfuncdin brs.cei get she cos6ofstwo d">= =else funcrsit retassa iftss=r/>In the foll .cei ssau?>= ='fn't es match?>= ='fasss match?>= =else = 1+010$d">= 2) thitbspnnually ore `mptain ord">funcmightelse In the foll >For exs:else = a1, 5, 8or;?php= a5, 1, 8or;?php=ult">lse = aiaoiord">=1, 'boiord">=2,t'coiord">='xyz'or;?php= aiaoiord">=1, 'coiord">='xyz', 'boiord">=2or;?php=ult">lse = a4iord">=1, 7iord">=2,t12iord">='xyz'or;?php= a9iord">=2,t3iord">=1, 123iord">='xyz'or;?php=ore `slse mrd">= else mrd">= else function = _ she cos$test(&nbr />&nqual": ((: : ((&nbr />&nbr />&nbr />  requal"  &n}else &nbr />&nqual": = _n't esegt;': ((  &n>: ((: = _n't esegt;': ((&nbr />&nqual": ((  &n>: ((: ((  &niftisset(: &nbr />&nbr />&nbr />  requal"  &n}else &nbr />&nqual": = _asssegt;': ((  &n>: ((: = _asssegt;': ((&nbr />&nqual": ((  &n>: ((: ((  &niftisset(: &nbr />&nbr />&nbr />  requal"  &n}else &nbr />&nqual"=n't eedihe dre ?;?php
  &n>: ((
: true= _asssegt;': ((: (= _asssegt;': ((: &nbr />&nbr />&nbr />&nqual"= as)else
&nbr />&nbr />&nbr />&negt;'
: &nbr />&nbr />&nbr />&nbr />&nbr />&nbr />&nbr />&negt;':           &n};?php
      &n};?php
  &n}else &nbr />  requal"
;t==).
up
0 12
7 years ago
<($a != 'hello'),ecal,I wondecompabosp;; isage The oce. rd">;< rd">;
< rd">;: ((: : ((: ((;<{ ;?php
  &n>: ((
tde-2' : : ((true:   &nfor">: ((: : ((: ((;
&n{ ;?php
  &nbr />&nbr />&nif(!bd">(
== :   &n} ;?php
  &n>: ((
: : ((truetster'. ; rd">;;< rd">;<#nif($a != 'hello') rd">;;;;< rd">;<#nif(!$a o= 'hello') rd">;;;
up
0 12
7 years ago
<($Profile['sk ===yle']=='0')? $lol = "sele eed":""r;?php<;?php
up
0 12
7 years ago
al,cannben..)fmpterd">= , my ri-dimensondit=1">= tpempubooleancore `fn't ee(iftdin querssfat ad swaexecute). Ineaus,n..)fmpterd">= />snoin'teou wan not rd">;< rd">;
< rd">;<$myA">= e-2' = a); ;?php< rd">;;= e-2' == ;<{ ;?php
    echo
; rd">;;;
up
0 12
7 years ago
:e===:

<?php<$ass="username == ;(== ;;: (() ? . . ',1"ng> i do="s?oing?' : (. ;(td">;al,> i you:e===:',1"ng> i do="s?e===:;; i DON'T get== is bsay r!;?php<;?php i get== is:else ',1"ng> i do="s? (so,forc />Hes is"Hello, "nbeforebit);?php i get== is:else ',1"ng> i do="s?;?php<;?php
<?php<$ass="username == ;(== ;;: (() ? . . ',1"ng> i do="s?oing?' : (. td">;en $iethi et, > i get== is:else ',1"ng> i do="s? (s ne eed)sr />en $iethiNOT et, > i get== is:else Im?), ( aso,).else i won'ayget=un e Nedr;rouhe pn ==1lw= ==knedeelsesu"ng> irbwing is do="stioly > i you: Tangright r any !==).
up
-3 12
7 years ago
;< rd">;
< rd">;<$z1e-2' : ;: (() ? : (() ? : (() ? == : ((;: ;: (() ? : (() ? : (() ? == : (( rd">;;s ne eedr;o tns ;< rd">; i eve=` Thget th rd">;< rd">;
< rd">;<$z1e-2' : : (() ? : (() ? : (() ? == : ((;: ;: (() ? : (() ? : (() ? == : (( rd">;;<(IF ? THEN : ELSE) rd">;<(IF ? THEN : ELSE(IF ? THEN : ELSE(IF ? THEN : ELSE)) rd">;< rd">;al,can'ay noreaNeeromoinsidee waout, un"72% a mathn Theula, ref, we6din logic lnr sst compabjHes is; is the. Inemathnnns ="s, > i e Ns; is olu>funcdin; isdeepns i 1lw= ==st">tdoutsideebeforebyor,.brs.ceiinside. (Logicss=", IF dinr wounn yahor THEN > i e Nssomes anytELSE wangetiinside. Oh,tdinr wound windowend We .ceiinside, nedeIF dinr wounasfridge THEN open sqlor ELSE > i st">ve.)!==).
up
-3 12
7 years ago
= nces fewe=`memberal />sm llss,eiftasseeromouage.sos1bjHes is Tund lnruage.sos2 treuld">= ==.ceiuntors.cthe , dinrwiwe6-,.brs.cein't eebern't ee(sea the foll >For ex).";?php<;?phpFor ex,.be co tain behaviour,ecal,sqliion is="diss=he obvious, so:e===:
al,diny dihe deeromo uld oll >achdn't eeindividually "72% $n't e1==$n't e2eberadd="stioly amoue se waynmfmpte($n't e1)==fmpte($n't e2)c uld eindin; ismix. In Tund tain osp;berinvns =ga e sb=ome (dinme) bizd">e behaviour.else <[Nuseb >al,ding>For ex,.bnthtnHen y==, jusayrd">=.sosult". Is'sgitHer seocebdioh2nerceivedly 'f, wesmfmpte()nain ire'.]e===:
6yift> i keep inemind taal,ding>For ex,in eies s dinr ord">func..s=r/ogitHelf nces rd">=.sosult"yiftt1.".uage.so==.ceid">= =,ecal,IMOsdefinis=he w"rth=stssany !===:
= asss doeion smreatr,afall ifta foreach()nw/>I wsea a 'dihe dre 'td">= . Aghtn,,.be cad by,ding>For ex,ecal,mighte now"rth=agoesonny !==).
up
-3 12
7 years ago
anys any",dingobjectwounalw= ==g be gr,< soselse"d">= =lt"ord">anys any",dingd">= />alw= ==g be gr.;?php<;?phpI wbe umad iending"keesedinyn1"ngli red. Inedin lreatrc..st,l"anys any",meanHe"anys anyg>Fcep < sgobject".;?php<;?phpa">= "eThis alw= ==decidee ial,dingobjectwoung be gr ( sosen't ate sway>positiv w ; sg Eornto no.bnsi ree ,a get sst compab"d">= =lt"ord">object"gmusayrlso alw= ==decidee ial,dingobjectwoung be gr ( sosen't ate sway>negativ w ; sg Eo !==).
up
-7 12
7 years ago
ore `),< sosso isg; is asayeromo ooleanctod ; sg Ei(vending&=describrounding ; sg Eitype:oore `-rd">0),ecal,tget asayeromo tis to ; sg Ei />undefinompand />In act== is sqlii curdre he in ee="coad byt asaoll oromo tis to ooleancand />Inyeromo ooleanctod ; sg Ei />s nlici he docu="coad (vending&=describrounding ; sg Eitype) aHesomes anyt= is sh/>I ws is noreeied pab(so tis==0 isg;ssa the beraccidee ,acal,(( ; )( ool) tis)==0 isg;ssa ageg.iecifice fun).;?php<;?phpfuncvending ; sg Eitypeg&=dinr wsh/>I wrlso noas"Convnrdrouneromoin sg E"wse">fun; similarly olseding dinr types !==).
up
-6 12
7 years ago
up
- 0 12
sm llboxsoftw1"ngnett com
7 years ago
&nFor >For ex: "700"m== "+700"mbsp; reassa fall th/>ghtdinyn1"ngtotally dihe dre ass="ss. ;?php<;?phpal,diny remain aHesss="ssedus="st sst compa.!==).
up
- 2 12
7 years ago
;;< rd">;thi="kkeoselseme: rd">;< rd">;
< rd">;;gh)dpemore `f dinrwiwe rd">;function : (((;<{ ;?php
    re">: ((
=bd">(: ((: ((;< rd">;;: ;: ;: ((: ((: ((: ((: ((;rd">valse": ;:   &n rd">;: ((: ((: ((: ((: ((;rd">valse"t==).
;page=language.operators.comparisonredirect=http://fr-not.netref="/maen/page=language.operators.compa-notfa img src='/imlans/"usernadd@2x.png' alt='adara "use' width='12'linight='12'>e">m ll>adara "usepa=m ll>para;> fun> 12 =e">fun>