比较运算符

比较运算符,如同它们名称所暗示的,允许对两个值进行比较。还可以参考 PHP 类型比较表看不同类型相互比较的例子。

表格 15-4. 比较运算符

例子名称结果
$a == $b等于TRUE,如果 $a 等于 $b。
$a === $b全等TRUE,如果 $a 等于 $b,并且它们的类型也相同。(PHP 4 引进)
$a != $b不等TRUE,如果 $a 不等于 $b。
$a <> $b不等TRUE,如果 $a 不等于 $b。
$a !== $b非全等TRUE,如果 $a 不等于 $b,或者它们的类型不同。(PHP 4 引进)
$a < $b小与TRUE,如果 $a 严格小于 $b。
$a > $b大于TRUE,如果 $a 严格 $b。
$a <= $b小于等于TRUE,如果 $a 小于或者等于 $b。
$a >= $b大于等于TRUE,如果 $a 大于或者等于 $b。

如果比较一个整数和字符串,则字符串会被转换为整数。如果比较两个数字字符串,则作为整数比较。此规则也适用于 switch 语句。

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

switch ("a") {
case
0:
    echo
"0";
    break;
case
"a": // never reached because "a" is already matched with 0
    
echo "a";
    break;
}
?>

对于多种的类型,比较运算符根据下表比较(按顺序)。

表格 15-5. 比较多种类型

运算数 1 类型运算数 1 类型结果
nullstringstringNULL 转换为 "",进行数字或词汇比较
boolnull任何其它类型转换为 boolFALSE < TRUE
objectobject 内置类可以定义自己的比较,不同类不能比较,相同类和数组同样方式比较属性(PHP 4 中),PHP 5 有其自己的说明
stringresourcenumberstringresourcenumber将字符串和资源转换成数字,按普通数学比较
arrayarray 具有较少成员的数组较小,如果运算数 1 中的键不存在于运算数 2 中则数组无法比较,否则挨个值比较(见下例)
array任何其它类型array 总是更大
object任何其它类型object 总是更大

例子 15-2. 标准数组比较代码

<?php
// 数组是用标准比较运算符这样比较的
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
}
?>

参见 strcasecmp()strcmp()数组运算符类型一章。

三元运算符

另一个条件运算符是“?:”(或三元)运算符 。

例子 15-3. 赋默认值

<?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'];
}

?>
表达式 (expr1) ? (expr2) : (expr3)expr1 求值为 TRUE 时的值为 expr2,在 expr1 求值为 FALSE 时的值为 expr3

注: 注意三元运算符是个语句,因此其求值不是变量,而是语句的结果。如果想通过引用返回一个变量这点就很重要。在一个通过引用返回的函数中语句 return $var == 42 ? $a : $b; 将不起作用,以后的 PHP 版本会为此发出一条警告。


add a note add a note User Contributed Notes
bishop
27-Oct-2006 06:49
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)
pcdinh at phpvietnam dot net
11-Aug-2006 12:50
You should be very careful when using == with an result set returned from a query that can be an empty array, multi-dimensional array or a boolean false value (if the query failed to execute). In PHP, an empty array is equivalent to true.

[php]
$myArray = array();

// check if there is any error with the query
if ($myArray == false)
{
   echo "Yes";
}

[/php]

return Yes

Use === instead.
gamephreak AT removethis gmail DOT com
18-Jul-2006 07:28
"Identical to" is faster compared to "equals to." I ran a test script that compared various combinations of strings and integers over a 10000x loop. Sample results:

'foo' v. 'foo' eq: 0.00274
'foo' v. 'foo' id: 0.001671
42 v. 42 eq: 0.00171
42 v. 42 id: 0.001436
'foo' v. 'bar' eq: 0.002589
'foo' v. 'bar' id: 0.001658
42 v. 43 eq: 0.001719
42 v. 43 id: 0.001419
'42' v. 42 eq: 0.00223
'42' v. 42 id: 0.001392
'42' v. 43 eq: 0.002281
'42' v. 43 id: 0.001389
Alex
17-May-2006 10:49
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 return true (because both are strings and == returns true), === actually returns false (which is good).
adam at caucho dot com
09-May-2006 01:49
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...
kroczu at interia dot pl
14-Feb-2006 09:26
<?
//attention about this case!

$a=0;

if(
$a=="some string..."){ /* (...) -> true! */ }
if(
$a==="some string..."){ /* (...) -> false */ }

$a=1;

if(
$a=="some string..."){ /*(...) -> false */ }
if(
$a==="some string..."){ /*(...) -> false */ }

?>
rshawiii at yahoo dot com
19-Jan-2006 03:36
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.

/**
 * 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
}
johnjc-phpdocs at publicinfo dot net
02-Nov-2005 02:41
The === and !== are not fully documented in either the Comparison Operator, Booleans type sections. They are talked about a bit more in the sections on strpos() and array_search() but those sections refer you to the section on Booleans for further information.

I am putting my contribution on === and !== in the Booleans section with pointers to it from the comment areas of other sections.

http://uk.php.net/manual/en/language.types.boolean.php
sam at liddicott dot com
01-Nov-2005 11:42
Don't be deceived into thinking that === compares objects for identity, it does not. It does a recusrive comparison which fails if there are recusrive object references involved, and will report as identical two different object instances that happen to merely have the same value.
You can see the stated problem at: http://bugs.php.net/bug.php?id=35053

My workaround is php::CompareObjects($a,$b)

# static class to hold methods to encapsulate php deficiencies in various versions
class php {
  # in === on objects in php4 does a dumb recusrive check instead
  function CompareObject(&$a,&$b) {
   $value='Bah! Stupid===';
   $key="bah".rand(0,1000);
   while(isset($a->$key)) $key.=rand(0,9);

   if (isset($b->$key)) return FALSE;
   $a->$key=$value;
   $result=($a->$key===$b->$key);
   unset($a->$key);
   return $result;
  }
}
08-Sep-2005 04:09
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
pandreas81 at NO dot gmx dot SPAM dot de
02-Jun-2005 06:40
Please note that the example in some notes before is not 100% correct, because it misses the call of abs().

To compare a float you should use abs($myFloat - 0.3) < EPSILON. This way of comparison is very common in other languages and it's cleaner than converting the values to strings. I suggest using a constant instead of a variable for EPSILON.
mita at abv dot bg
24-Mar-2005 10:34
Float values comparation:

if ( (string) $a == (string) $b) {
  print 'a is equal to b';
} else {
  print 'a is not equal to b';
}
sven dot heyll at web dot de
05-Dec-2004 05:19
Hi folks,
to the float comparison problem...

This worked for me:

//! compare two floating point values, return true if they are equal
//! (enough) or false otherwise
function float_equal($f1, $f2)
{
   return ($f1 > $f2) ? (false) : (!($f1 < $f2));
}

// compare floats
$f1 = 0.037;
$f2 = 1000387.978;
echo "$f1 and $f2 are ".(float_equal($f1,$f2)?("equal"):("not equal"))."<br />";
$f1 = 0.3;
$f2 = 0.3;   
echo "$f1 and $f2 are ".(float_equal($f1,$f2)?("equal"):("not equal"))."<br />";
02-Dec-2004 07:47
Concerning floats: It is simply pointless to compare a float with the value "0.3". The number 0.3 is not exactly representable in binary. Period. So is the number 0.1, and an infinite number of others numbers. Just like 1/3 is not exactly representable in decimal. How would you code the test for your float to be one third? Maybe $myFloat == 0.33333333333  Hmm: you see: Everyone would agree that this test is not accurate.

The test $myFloat == 0.3 is making exactly the same mistake.

So the float which you think should be 0.3 is really something very close to it; if you print it in decimal, the conversion will end up with the closest decimal representation, which may well be "0.3". But "0.3" is also the "right display decimal" for hundreds of float values.

The correct way to "compare" floats is: ( $myFloat - 0.3 ) < $EPSILON where $EPSILON is something like 1e-10, depending on your application. Approximate algorithms are the only right way to treat floats, which are only approximate by themselves.
darkcryst at gmail dot com
21-Oct-2004 06:35
be REALLY careful when comparing float values. PHP, like most languages, is vunerable to he problems of floating point precision.

Do NOT compare floats directly, and this also means any decimal value at all.

The headaches finding out if $var = 0.3 caused me are unbelievable. even though the stored variable WAS 0.3 it was still ignoring it - this was to do with the internal float not recognising it as 0.3 even though it *displayed* it as 0.3 when echo'd or printed... basically it was stored imprecisly, but not able to display it as such.

I ended up having to compare after multiplying by 10, rounding, and then dividing by 10... rediculous, but sadly the only way I could find to reliably do it. The round seemed to remove the break in the float...

jesus that took me ages to find...
hiroh2k at yahoo dot com
20-Oct-2004 02:05
if you want to use the ?: operator, you should be careful with the precedence.

Here's an example of the priority of operators:

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.

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.
jeronimo at DELETE_THIS dot transartmedia dot com
02-Jul-2004 07:01
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...

<?

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...

<?

// 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

?>
webmaster __AT__ digitalanime __DOT__ nl
14-Apr-2004 06:31
WARNING!!!!

Let's say, we have this little script:

<?php
$username
= 'Me';
$guestusername = 'Guest';

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

What you want:
If $i is set, display:
Hello, my friend: Me, how are you doing?
If not, display:
Hello, my guest, Guest, please register

BUT, you DON'T get that result!

If $i is set, you get this:
my friend: Me, how are you doing? (so, there's not "Hello, " before it)
If $i is NOT set, you get this:
my friend: Me, how are you doing?

So... That's the same!

You can solve this by using the "(" and ")" to give priority to the ternary operator:

<?php
$username
= 'Me';
$guestusername = 'Guest';

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

When $i is set, you get this:
Hello, my friend: Me, how are you doing? (expected)
When $i is NOT set, you get this:
Hello, my guest, Guest, please register (expected too)

So.. Please, don't be dumb and ALWAYS use the priority-signs (or.. How do you call them?), ( and ).
By using them, you won't get unneeded trouble and always know for sure your code is doing what you want: The right thing.
user@example
04-Apr-2004 06:17
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....!!
gphemsley at users dot sourceforge dot net
04-Jan-2004 08:15
For those of you who need to use === with PHP 3, this should do the trick:

<?php

function is_identical( $left, $right )
{
   if(
phpversion() >= 4 )
   {
       return (
$left === $right );
   }
   else
   {
       if( (
$left == $right ) && ( gettype( $left ) == gettype( $right ) ) )
       {
           return
TRUE;
       }
       else
       {
           return
FALSE;
       }
   }
}

?>

1 === '1' is the same as is_identical( 1, '1' ).
jwhiting at hampshire dot edu
10-Dec-2003 07:31
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...
mina86 at tlen dot pl
04-Dec-2003 07:03
I guess quicker method would be:

<?php
$colors
= array('#EEEEEE', '#FFFFFF');
while (
$i++ < 10) {
?>
    <tr bgColor="<?=$colors[$i%2]?>">
       <td>Cell 1-<?=$i?></td>
       <td>Cell 2-<?=$i?></td>
       <td>Cell 3-<?=$i?></td>
       <td>Cell 4-<?=$i?></td>
   </tr>
<?php } ?>

And you can easily add more colors:

<?php
$colors
= array('#EEEEEE', '#FFFFFF', '#DDDDDD', '#CCCCCC');
while (
$i++ < 10) {
?>
    <tr bgColor="<?=$colors[$i%4]?>">
       <td>Cell 1-<?=$i?></td>
       <td>Cell 2-<?=$i?></td>
       <td>Cell 3-<?=$i?></td>
       <td>Cell 4-<?=$i?></td>
   </tr>
<?php } ?>
xhenxhe
13-Nov-2003 10:27
This operator is very is usefull and will save you time and lines once you get the hang of it. Try this next time you are looping through rows in a table and want to change the bgColor:

<table border=1 width=100% align=center style="border-collapse: collapse" bgColor="lightblue">
   <tr>
       <td>Column 1</td>
       <td>Column 2</td>
       <td>Column 3</td>
       <td>Column 4</td>
   </tr>
<?
  
while ($i++ < 10)
   {
      
$rbg = $rbg=="#EEEEEE" ? "#FFFFFF" : "#EEEEEE";
?>
    <tr bgColor="<?=$rbg?>">
       <td>Cell 1-<?=$i?></td>
       <td>Cell 2-<?=$i?></td>
       <td>Cell 3-<?=$i?></td>
       <td>Cell 4-<?=$i?></td>
   </tr>
<?    } ?>
</table>