PHP 中的 3 种不同比较,=、==、===

问题描述 投票:0回答:5

=
==
===
有什么区别?

我认为使用一个

=
是声明一个变量,而
==
是用于比较条件,最后
===
是用于比较声明变量的值。

php comparison operators
5个回答
179
投票

您有

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

$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)

有关

==
===
的需求以及各自使用情况的更多信息,请参阅 文档


23
投票
  • =
    是赋值运算符
  • ==
    是比较运算符(检查是否 两个变量具有相同的值)
  • ===
    是相同的比较 运算符(检查两个变量是否 具有相同的值并且相同 类型)。

9
投票

= 赋值运算符

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

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


3
投票

= 运算符将值赋给变量 $六 = 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 类型。所以这里的输出


0
投票

对于高级 PHP 用户,了解

==
===
之间的区别,并问自己“当我确定两个操作数是相同类型时,与
==
比较还是与
===
比较更快?”

简短而笼统的答案是:在这种情况下使用

===
不会带来性能提升,因此您可能应该使用
==

对于那些有兴趣自己进行基准测试的人,您可以使用我临时编写的以下代码,并尝试

$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";
?>

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

© www.soinside.com 2019 - 2024. All rights reserved.