本文将讨论 PHP 中”==”和”===”操作符之间的区别。两者都是比较运算符,用于比较两个或多个值。
== 操作符: 该操作符用于检查给定值是否相等。如果是,则返回 true
,否则返回 false
。
语法:
operand1 == operand2
=== 操作符: 该操作符用于检查给定值及其数据类型是否相等。如果是,则返回 true
,否则返回 false
。
语法:
operand1 === operand2
注意:当操作数的数据类型不同时,
===
运算符将返回false
。
例1: 下面的代码演示了操作数数据类型相同和不同的 ==
运算符。
<?php
$a = 1234;
$b = 1234;
// Show message if two operands are
// equal with same data type operands
if($a == $b) {
echo "Equal";
}
else{
echo "Not Equal";
}
// Show a message if two operands are equal
// with different data type operands
// First is of string type and the second
// is of integer type
if('1234' == 1234){
echo "Equal";
}
else{
echo "Not Equal";
}
?>
运行结果:
Equal
Equal
示例2: 下面的代码演示了 === 操作符。
<?php
$a = 1234;
$b = 1234;
// Return a message if two operands are
// equal with same data type operands
if($a === $b){
echo "Equal";
}
else{
echo "not Equal";
}
// Return a message if two operands are equal
// with different data type operands
// First is of string type and the second
// is if integer type
if('1234' === 1234){
echo "Equal";
}
else{
echo "not Equal";
}
?>
运行结果:
Equal
not Equal
== 和 === 操作符之间的区别:
== |
=== |
---|---|
== 是等于运算符。 |
=== 是相同运算符。 |
用于检查两个操作数是否相等。 | 用于检查两个操作数及其数据类型是否相等。 |