3个不同的等于

b5buobof  于 2021-06-20  发布在  Mysql
关注(0)|答案(5)|浏览(389)

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

xggvc2p6

xggvc2p61#

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

fivyi3re

fivyi3re2#

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

hfsqlsce

hfsqlsce3#

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

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

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

axzmvihb

axzmvihb4#

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

u2nhd7ah

u2nhd7ah5#

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

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

相关问题