三个不同的等于

======之间的区别是什么?

我认为使用一个等号是为了声明一个变量,而两个等号是为了比较条件,最后三个等号是为了比较声明的变量的值。

48891 次浏览

你有 =赋值运算符赋值运算符==“相等”比较运算符===“相同”比较运算符

$a = $b     Assign      Sets $a to be equal to $b.
$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)

要了解更多关于 =====的需求以及使用它们的情况的信息,请查看 那些文件

= 赋值运算符

= = 检查两个变量的值是否相同

= = = 检查两个变量的值是否相同,以及它们的类型是否相同

  • =是赋值运算符
  • 是比较运算符(检查是否 两个变量的值相等)
  • ===是相同的比较 操作符(检查是否有两个变量 具有相等的值,且具有相同的 类别)。

对于高级 PHP 用户,了解 =====之间的区别,并问自己“当我确定两个操作数是同一类型时,与 =====比较是否更快?”

简短而笼统的答案是: 在这种情况下,使用 ABC0不会提高性能,因此您可能应该使用 ==

对于那些对基准测试感兴趣的人,您可以使用我特别编写的以下代码,并尝试使用 $a$b的不同值:

<?php
// CONFIGURATION
$cycles = 1000000;
$a = 'random string 1';
$b = 'random string 2';


// FUNCTIONS
function compare_two_equals($a, $b) {
if ($a == $b) {
return TRUE;
} else {
return FALSE;
}
}


function compare_three_equals($a, $b) {
if ($a === $b) {
return TRUE;
} else {
return FALSE;
}
}


// EXECUTION
$time = microtime(TRUE);
for ($count_a = 0; $count_a < $cycles; $count_a++) {
compare_two_equals($a, $b);
}
$time_two_a = microtime(TRUE) - $time;
$time = microtime(TRUE);
for ($count_a = 0; $count_a < $cycles; $count_a++) {
compare_three_equals($a, $b);
}
$time_three_a = microtime(TRUE) - $time;
$time = microtime(TRUE);
for ($count_a = 0; $count_a < $cycles; $count_a++) {
compare_two_equals($a, $b);
}
$time_two_b = microtime(TRUE) - $time;
$time = microtime(TRUE);
for ($count_a = 0; $count_a < $cycles; $count_a++) {
compare_three_equals($a, $b);
}
$time_three_b = microtime(TRUE) - $time;
$time = microtime(TRUE);


// RESULTS PRINTING
print "<br />\nCOMPARE == (FIRST TRY): " . number_format($time_two_a, 3) . " seconds";
print "<br />\nCOMPARE == (SECOND TRY): " . number_format($time_two_b, 3) . " seconds";
print "<br />\nCOMPARE === (FIRST TRY): " . number_format($time_three_a, 3) . " seconds";
print "<br />\nCOMPARE === (SECOND TRY): " . number_format($time_three_b, 3) . " seconds";
?>

注意: 只有当每个“第一次尝试”非常接近其“第二次尝试”时,比较才有效。如果它们明显不同,则意味着处理器在执行比较时正忙于执行其他操作,因此结果是不可靠的,应该再次运行基准测试。

= 运算符将值赋给一个变量 $six = 6; 值6被赋给变量 $six

= = 运算符检查两个变量的值是否相等,并且主要用于诸如 if 语句之类的条件

$a = 2;
$b = 2;
if ($a == $b) {
echo both variables have the same value;
}

= = = 类似于 = = 的运算符(检查值是否相等) ,并检查两个数据类型是否相同

$a = 2;
$b = "2";
if ($a === $b) {
echo "both variable have same value and of same data type";
} else {
echo 'both variable is either not equal or not of same data type';
}

//这里 $a 的类型是 int,而 $b 的类型是 string