3个不同的等于

eblbsuwk  于 2021-06-18  发布在  Mysql
关注(0)|答案(5)|浏览(335)

两者有什么区别 = , == ,和 === ?
我认为使用一个等号声明一个变量,而两个等号表示比较条件,最后三个等号表示比较声明变量的值。

axkjgtzd

axkjgtzd1#

= 是赋值运算符 == 是比较运算符(检查两个变量的值是否相等) === 是相同的比较运算符(检查两个变量的值是否相等以及类型是否相同)。

m1m5dgzv

m1m5dgzv2#

=运算符将值赋给变量$six=6;值6分配给变量$6
==运算符检查两个变量的值是否相等,主要用于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类型。所以这里是输出

q35jwt9p

q35jwt9p3#

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

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

更多关于 == 以及 === ,以及使用每种方法的情况,请查看文档。

sc4hvdpw

sc4hvdpw4#

对于高级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";
?>

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

9gm1akwq

9gm1akwq5#

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

相关问题