PHP 比较操作符

Comparison Operators
ExampleNameResult
$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 1Type of Operand 2Result
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自作聪明的进行自动类型转换。

posted @   浪淘沙(Jeff.Liu)  阅读(1175)  评论(0编辑  收藏  举报
编辑推荐:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示