PHP 比較操作符

來源:互聯網
上載者:User
Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$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.

 

注意:如果將字串和一個integer類型的值比較。string會轉化為number類型(integer類型或者float類型),然後再和integer進行比較。

 

 1 <?php
2  var_dump(0 == "a"); // 0 == 0 -> true
3  var_dump("1" == "01"); // 1 == 1 -> true
4 var_dump("1" == "1e0"); // 1 == 1 -> true
5
6 switch ("a") {
7 case 0:
8 echo "0";
9 break;
10 case "a": // never reached because "a" is already matched with 0
11 echo "a";
12 break;
13 }
14 ?>
15

 

 

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 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)
array anything array is always greater
object anything object is always greater

 

在進行比較兩個數的時候,最好先把這個表中的意思全部理解了。才好。

我曾經就在這個吃過虧。

 

還有就是,在比較兩個value的時候,如果能使用 “===”和“!==”操作符的時候就使用這兩個操作符。 以免php自作聰明的進行自動類型轉換。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.