有什么区别 =====?

  • 松散究竟如何 == 比较工作?
  • 具体如何严格 === 比较工作?

有哪些有用的例子?

有帮助吗?

解决方案

之间的区别 =====

松散的区别 == 等于运算符和严格运算符 === 相同的运算符在中得到了准确的解释 手动的:

比较运算符

┌──────────┬───────────┬───────────────────────────────────────────────────────────┐
│ Example  │ Name      │ Result                                                    │
├──────────┼───────────┼───────────────────────────────────────────────────────────┤
│$a ==  $b │ Equal     │ TRUE if $a is equal to $b after type juggling.            │
│$a === $b │ Identical │ TRUE if $a is equal to $b, and they are of the same type. │
└──────────┴───────────┴───────────────────────────────────────────────────────────┘

宽松地 == 平等比较

如果您正在使用 == 运算符,或任何其他使用松散比较的比较运算符,例如 !=, <> 或者 ==, ,你总是要看看 语境 看看什么东西、在哪里以及为什么被转换,以了解正在发生的事情。

转换规则

类型对照表

作为参考和示例,您可以查看以下比较表 手动的:

松散比较 ==

┌─────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬─────────┬───────┬───────┐
│         │ TRUE  │ FALSE │   1   │   0   │  -1   │  "1"  │  "0"  │ "-1"  │ NULL  │ array() │ "php" │  ""   │
├─────────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼─────────┼───────┼───────┤
│ TRUE    │ TRUE  │ FALSE │ TRUE  │ FALSE │ TRUE  │ TRUE  │ FALSE │ TRUE  │ FALSE │ FALSE   │ TRUE  │ FALSE │
│ FALSE   │ FALSE │ TRUE  │ FALSE │ TRUE  │ FALSE │ FALSE │ TRUE  │ FALSE │ TRUE  │ TRUE    │ FALSE │ TRUE  │
│ 1       │ TRUE  │ FALSE │ TRUE  │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ 0       │ FALSE │ TRUE  │ FALSE │ TRUE  │ FALSE │ FALSE │ TRUE  │ FALSE │ TRUE  │ FALSE   │ TRUE  │ TRUE  │
│ -1      │ TRUE  │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE   │ FALSE │ FALSE │
│ "1"     │ TRUE  │ FALSE │ TRUE  │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ "0"     │ FALSE │ TRUE  │ FALSE │ TRUE  │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ "-1"    │ TRUE  │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE   │ FALSE │ FALSE │
│ NULL    │ FALSE │ TRUE  │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE  │ TRUE    │ FALSE │ TRUE  │
│ array() │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE  │ TRUE    │ FALSE │ FALSE │
│ "php"   │ TRUE  │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE   │ TRUE  │ FALSE │
│ ""      │ FALSE │ TRUE  │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE   │ FALSE │ TRUE  │
└─────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴─────────┴───────┴───────┘

严格的 === 相同比较

如果您正在使用 === 运算符,或任何其他使用严格比较的比较运算符,例如 !== 或者 ===, ,那么你总是可以确定类型不会 神奇地 改变,因为不会发生任何转换。因此,通过严格比较,类型和值必须相同,而不仅仅是值。

类型对照表

作为参考和示例,您可以查看以下比较表 手动的:

严格比较 ===

┌─────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬─────────┬───────┬───────┐
│         │ TRUE  │ FALSE │   1   │   0   │  -1   │  "1"  │  "0"  │ "-1"  │ NULL  │ array() │ "php" │  ""   │
├─────────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼─────────┼───────┼───────┤
│ TRUE    │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ FALSE   │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ 1       │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ 0       │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ -1      │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ "1"     │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ "0"     │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE │ FALSE   │ FALSE │ FALSE │
│ "-1"    │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE │ FALSE   │ FALSE │ FALSE │
│ NULL    │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE  │ FALSE   │ FALSE │ FALSE │
│ array() │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ TRUE    │ FALSE │ FALSE │
│ "php"   │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE   │ TRUE  │ FALSE │
│ ""      │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE │ FALSE   │ FALSE │ TRUE  │
└─────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴─────────┴───────┴───────┘

其他提示

如果两个不同类型不同,则运算符 == 在它们之间进行强制转换,而 === 运算符则执行“类型安全比较”。这意味着只有两个操作数具有相同类型和相同值时才会返回 true。

例子:

1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // "1" gets casted to an integer, which is 1
"foo" === "foo": true // both operands are strings and have the same value

警告:具有等效成员的同一类的两个实例不匹配 === 操作员。例子:

$a = new stdClass();
$a->foo = "bar";
$b = clone $a;
var_dump($a === $b); // bool(false)

一张图片胜过千言万语:

PHP 双等于 == 等式图:

enter image description here

PHP 三等号 === 等式图:

enter image description here

创建这些图像的源代码:

https://github.com/sentientmachine/php_equality_charts

上师冥想

那些希望保持理智的人请不要继续阅读,因为除了说 PHP 的疯狂分形就是这样设计的之外,这些都没有任何意义。

  1. NAN != NANNAN == true.
  2. == 如果 left 是数字,则将左操作数和右操作数转换为数字。所以 123 == "123foo", , 但 "123" != "123foo"
  3. 引号中的十六进制字符串有时是浮点数,并且会意外地转换为违背您意愿的浮点数,从而导致运行时错误。

  4. == 不具有传递性,因为 "0"== 0, , 和 0 == """0" != ""

  5. PHP 尚未声明的变量为 false,尽管 PHP 有一种方法来表示未定义的变量,但该功能已被禁用 ==.
  6. "6" == " 6", "4.2" == "4.20", , 和 "133" == "0133"133 != 0133. 。但 "0x10" == "16""1e3" == "1000" 在未经您的指示或同意的情况下,将发生意外的字符串转换为八进制,从而导致运行时错误。

  7. False == 0, "", []"0".

  8. 当数字足够大时,它们 == 无穷大。

  9. 新的班级是 == 到 1。

  10. False 是最危险的值,因为 False 对于大多数其他变量来说都是==,这很大程度上违背了它的目的。

希望:

如果您使用 PHP,则不应使用双等号运算符,因为如果您使用三等号,则唯一需要担心的边缘情况是 NAN 和接近无穷大的数字,以至于它们会被强制转换为无穷大。有了双等号,任何事情都可以是惊喜 == 对任何事情或,或可能会违背您的意愿而出其不意,并且 != 显然它应该等于的东西。

无论您在哪里使用 == PHP 中的代码味道很糟糕,因为其中的 85 个错误是由隐式转换规则暴露出来的,这些规则似乎是由数百万程序员通过布朗运动编程设计的。

关于 JavaScript:

=== 运算符的工作方式与 == 运算符相同,但它要求其操作数不仅具有相同的值,而且具有相同的数据类型。

例如,下面的示例将显示“x 和 y 相等”,但不显示“x 和 y 相同”。

var x = 4;
var y = '4';
if (x == y) {
    alert('x and y are equal');
}
if (x === y) {
    alert('x and y are identical');
}

关于对象比较的其他答案的补充:

== 使用对象的名称及其值来比较对象。如果两个对象具有相同的类型并且具有相同的成员值, $a == $b 产生 true。

=== 比较对象的内部对象 ID。即使成员平等, $a !== $b 如果它们不是完全相同的对象。

class TestClassA {
    public $a;
}

class TestClassB {
    public $a;
}

$a1 = new TestClassA();
$a2 = new TestClassA();
$b = new TestClassB();

$a1->a = 10;
$a2->a = 10;
$b->a = 10;

$a1 == $a1;
$a1 == $a2;  // Same members
$a1 != $b;   // Different classes

$a1 === $a1;
$a1 !== $a2; // Not the same object

用最简单的话来说:

== 检查是否 相等的 (仅值)

=== 检查是否 相同的 (值类型)


等效对比相同的:一个类比

1 + 1 = 2 + 0 (相等的)

1 + 1 = 1 + 1 (相同的)


在 PHP 中:

真 == 1 (真实 - 等值)

真 === 1 (false - 值 && 类型不同)

  • 真实的是 布尔值
  • 1 是 整数

这都是关于数据类型的。采取一个 BOOL (正确或错误)例如:

true 也等于 1false 也等于 0

== 比较时不关心数据类型:因此,如果你有一个变量为 1(也可以是 true):

$var=1;

然后与 ==:

if ($var == true)
{
    echo"var is true";
}

$var 实际上并不等于 true, , 可以?它的 int 值为 1 相反,这又等于 true。

===, ,检查数据类型以确保两个变量/对象/任何内容使用相同的类型。

所以如果我这样做了

if ($var === true)
{
    echo "var is true";
}

这个条件不会成立,因为 $var !== true 它只是 == true (如果你明白我的意思)。

你为什么需要这个?

很简单——让我们看一下 PHP 的一个函数: array_search():

array_search() 函数只是在数组中搜索值,并返回找到该值的元素的键。如果在数组中找不到该值,则返回 错误的. 。但是,如果你做了一个 array_search() 存储在一个值上 数组的第一个元素 (数组键为 0)....这 array_search() 函数将返回 0...等于 false..

所以如果你这样做:

$arr = array("name");
if (array_search("name", $arr) == false)
{
    // This would return 0 (the key of the element the val was found
    // in), but because we're using ==, we'll think the function
    // actually returned false...when it didn't.
}

那么,您知道这现在怎么会成为一个问题吗?

大多数人不使用 == false 当检查函数是否返回 false 时。相反,他们使用 !. 。但实际上,这与使用完全相同 ==false, ,所以如果你这样做:

$arr = array("name");
if (!array_search("name", $arr)) // This is the same as doing (array_search("name", $arr) == false)

所以对于这样的事情,你会使用 === 相反,以便检查数据类型。

一个示例是数据库属性可以为 null 或“”:

$attributeFromArray = "";
if ($attributeFromArray ==  ""){}  //true
if ($attributeFromArray === ""){}  //true
if ($attributeFromArray ==  null){}  //true
if ($attributeFromArray === null){}  //false

$attributeFromArray = null;
if ($attributeFromArray ==  ""){}  //true
if ($attributeFromArray === ""){}  //false
if ($attributeFromArray ==  null){}  //true
if ($attributeFromArray === null){}  //true

给定 x = 5

1) 操作员:== 是“等于”。 x == 8 是假的
2) 操作员:=== 是“完全等于”(值和类型) x === 5 是真的, x === "5" 是假的

举几个例子

var_dump(5 == 5);    // True
var_dump(5 == "5");  // True because == checks only same value not type
var_dump(5 === 5);   // True
var_dump(5 === "5"); // False because value are same but data type are different.

附:

== 只比较值,不关心数据类型

=== 比较值和数据类型

$a = 5;   // 5 as an integer

var_dump($a == 5);       // compare value; return true
var_dump($a == '5');     // compare value (ignore type); return true
var_dump($a === 5);      // compare type/value (integer vs. integer); return true
var_dump($a === '5');    // compare type/value (integer vs. string); return false

不过要小心。这是一个臭名昭著的问题。

// 'test' is found at position 0, which is interpreted as the boolean 'false'
if (strpos('testing', 'test')) {
    // code...
}

// true, as strict comparison was made (0 !== false)
if (strpos('testing', 'test') !== false) {
    // code...
}

简而言之,=== 的工作方式与 == 在大多数其他编程语言中的工作方式相同。

PHP 允许您进行没有实际意义的比较。例子:

$y = "wauv";
$x = false;
if ($x == $y)
    ...

虽然这允许一些有趣的“快捷方式”,但您应该小心,因为返回不应该返回的内容(例如“错误”而不是数字)的函数不会被捕获,并且您会想知道发生了什么。

在 PHP 中,== 会比较值并在必要时执行类型转换(例如,字符串“12343sdfjskfjds”在整数比较中将变为“12343”)。=== 将比较值与类型,如果类型不同则返回 false。

如果你查看 PHP 手册,你会发现很多函数在函数失败时返回“false”,但在成功的情况下它们可能返回 0,这就是为什么他们建议执行“if (function() !== false)”以避免错误。

您可以使用 === 来测试函数或变量是否为 false,而不仅仅是等于 false(零或空字符串)。

$needle = 'a';
$haystack = 'abc';
$pos = strpos($haystack, $needle);
if ($pos === false) {
    echo $needle . ' was not found in ' . $haystack;
} else {
    echo $needle . ' was found in ' . $haystack . ' at location ' . $pos;
}

在这种情况下,strpos 将返回 0,这在测试中相当于 false

if ($pos == false)

或者

if (!$pos)

这不是你想要的。

至于何时使用其中一种而不是另一种,以 fwrite() PHP 中的函数。

该函数将内容写入文件流。根据 PHP 的说法,“fwrite() 返回写入的字节数,如果出错则返回 FALSE。”。如果你想测试函数调用是否成功,这个方法是有缺陷的:

if (!fwrite(stuff))
{
    log('error!');
}

它可以返回零(并被认为是成功的),并且您的条件仍然会被触发。正确的方法是:

if (fwrite(stuff) === FALSE)
{
    log('error!');
}

PHP 是一种松散类型语言。使用双等于运算符可以对变量进行松散检查。

松散地检查一个值将允许一些相似但不相等的值相等:

  • ''
  • 无效的
  • 错误的
  • 0

使用双等于运算符,所有这些值都将相等。

php == 是一个比较运算符,用于比较变量的值。但 === 比较的是值和数据类型。

例如,

<?php 
  $var1 = 10;
  $var2 = '10';

  if($var1 == $var2) {
    echo 'Variables are equal';
  } else {
    echo 'Variables are not equal';
  }
?>

在这种情况下,输出将为“变量相等”,即使它们的数据类型不同。

但如果我们使用 === 而不是 ==,输出将是“变量不相等”。php首先比较变量的值,然后比较数据类型。这里的值是相同的,但数据类型不同。

变量有类型和值。

  • $var = "test" 是包含“test”的字符串
  • $var2 = 24 是一个整数,vhose 值为 24。

当您使用这些变量(在 PHP 中)时,有时您没有好的类型。例如,如果你这样做

if ($var == 1) {... do something ...}

PHP 必须将 $var 转换(“转换”)为整数。在本例中,“$var == 1”为 true,因为任何非空字符串都会转换为 1。

使用 === 时,您检查值和类型是否相等,因此“$var === 1”为 false。

这很有用,例如,当您有一个可以返回 false(出错时)和 0(结果)的函数时:

if(myFunction() == false) { ... error on myFunction ... }

这段代码是错误的,好像 myFunction() 返回 0,它被转换为 false,你似乎有一个错误。正确的代码是:

if(myFunction() === false) { ... error on myFunction ... }

因为测试是返回值“是一个布尔值并且是 false”而不是“可以转换为 false”。

=== 运算符应该比较 精确的 内容平等,同时 == 运算符会比较语义相等性。特别是它会将字符串强制转换为数字。

平等是一个广阔的主题。看 维基百科关于平等的文章.

<?php

    /**
     * Comparison of two PHP objects                         ==     ===
     * Checks for
     * 1. References                                         yes    yes
     * 2. Instances with matching attributes and its values  yes    no
     * 3. Instances with different attributes                yes    no
     **/

    // There is no need to worry about comparing visibility of property or
    // method, because it will be the same whenever an object instance is
    // created, however visibility of an object can be modified during run
    // time using ReflectionClass()
    // http://php.net/manual/en/reflectionproperty.setaccessible.php
    //
    class Foo
    {
        public $foobar = 1;

        public function createNewProperty($name, $value)
        {
            $this->{$name} = $value;
        }
    }

    class Bar
    {
    }
    // 1. Object handles or references
    // Is an object a reference to itself or a clone or totally a different object?
    //
    //   ==  true   Name of two objects are same, for example, Foo() and Foo()
    //   ==  false  Name of two objects are different, for example, Foo() and Bar()
    //   === true   ID of two objects are same, for example, 1 and 1
    //   === false  ID of two objects are different, for example, 1 and 2

    echo "1. Object handles or references (both == and    ===) <br />";

    $bar = new Foo();    // New object Foo() created
    $bar2 = new Foo();   // New object Foo() created
    $baz = clone $bar;   // Object Foo() cloned
    $qux = $bar;         // Object Foo() referenced
    $norf = new Bar();   // New object Bar() created
    echo "bar";
    var_dump($bar);
    echo "baz";
    var_dump($baz);
    echo "qux";
    var_dump($qux);
    echo "bar2";
    var_dump($bar2);
    echo "norf";
    var_dump($norf);

    // Clone: == true and === false
    echo '$bar == $bar2';
    var_dump($bar == $bar2); // true

    echo '$bar === $bar2';
    var_dump($bar === $bar2); // false

    echo '$bar == $baz';
    var_dump($bar == $baz); // true

    echo '$bar === $baz';
    var_dump($bar === $baz); // false

    // Object reference: == true and === true
    echo '$bar == $qux';
    var_dump($bar == $qux); // true

    echo '$bar === $qux';
    var_dump($bar === $qux); // true

    // Two different objects: == false and === false
    echo '$bar == $norf';
    var_dump($bar == $norf); // false

    echo '$bar === $norf';
    var_dump($bar === $norf); // false

    // 2. Instances with matching attributes and its values (only ==).
    //    What happens when objects (even in cloned object) have same
    //    attributes but varying values?

    // $foobar value is different
    echo "2. Instances with matching attributes  and its values (only ==) <br />";

    $baz->foobar = 2;
    echo '$foobar' . " value is different <br />";
    echo '$bar->foobar = ' . $bar->foobar . "<br />";
    echo '$baz->foobar = ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // false

    // $foobar's value is the same again
    $baz->foobar = 1;
    echo '$foobar' . " value is the same again <br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$baz->foobar is ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // true

    // Changing values of properties in $qux object will change the property
    // value of $bar and evaluates true always, because $qux = &$bar.
    $qux->foobar = 2;
    echo '$foobar value of both $qux and $bar is 2, because $qux = &$bar' . "<br />";
    echo '$qux->foobar is ' . $qux->foobar . "<br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$bar == $qux';
    var_dump($bar == $qux); // true

    // 3. Instances with different attributes (only ==)
    //    What happens when objects have different attributes even though
    //    one of the attributes has same value?
    echo "3. Instances with different attributes (only ==) <br />";

    // Dynamically create a property with the name in $name and value
    // in $value for baz object
    $name = 'newproperty';
    $value = null;
    $baz->createNewProperty($name, $value);
    echo '$baz->newproperty is ' . $baz->{$name};
    var_dump($baz);

    $baz->foobar = 2;
    echo '$foobar' . " value is same again <br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$baz->foobar is ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // false
    var_dump($bar);
    var_dump($baz);
?>

到目前为止,所有答案都忽略了 === 的危险问题。顺便指出,但没有强调,整数和双精度是不同的类型,因此以下代码:

$n = 1000;
$d = $n + 0.0e0;
echo '<br/>'. ( ($n ==  $d)?'equal' :'not equal' );
echo '<br/>'. ( ($n === $d)?'equal' :'not equal' );

给出:

 equal
 not equal

请注意,这不是“舍入错误”的情况。这两个数字直到最后一位都完全相等,但它们具有不同的类型。

这是一个令人讨厌的问题,因为如果所有数字都足够小,则使用 === 的程序可以运行多年(其中“足够小”取决于您运行的硬件和操作系统)。但是,如果碰巧某个整数恰好足够大,可以转换为双精度型,则其类型将“永远”更改,即使后续操作或许多操作可能会将其值恢复为小整数。而且,情况变得更糟。它可以传播——双重感染可以传播到它接触到的任何东西,一次一个计算。

例如,在现实世界中,这可能是处理 2038 年之后日期的程序中的一个问题。此时,UNIX 时间戳(自 1970-01-01 00:00:00 UTC 以来的秒数)将需要超过 32 位,因此它们的表示形式将在某些系统上“神奇地”切换为双倍。因此,如果您计算两个时间之间的差异,您最终可能会得到几秒钟的结果,但结果是双精度数,而不是 2017 年出现的整数结果。

我认为这比字符串和数字之间的转换要糟糕得多,因为它很微妙。我发现跟踪什么是字符串和什么是数字很容易,但是跟踪数字中的位数超出了我的范围。

因此,在上面的答案中,有一些不错的表格,但 1(作为整数)和 1(微妙双精度)和 1.0(明显双精度)之间没有区别。另外,建议您应该始终使用 === 而从不使用 == ,这种建议并不好,因为 === 有时会在 == 正常工作的情况下失败。另外,JavaScript 在这方面并不等效,因为它只有一种数字类型(内部可能有不同的按位表示,但不会导致 === 出现问题)。

我的建议是——两者都不用。您需要编写自己的比较函数才能真正解决这个问题。

之间有两个区别 ===== 在 PHP 数组和对象中,我认为这里没有提到;两个具有不同键排序的数组和对象。

两个具有不同键排序的数组

如果您有一个具有键排序的数组和另一个具有不同键排序的数组,则它们是完全不同的(即使用 ===)。如果您对数组进行键排序,并尝试将排序后的数组与原始数组进行比较,则可能会导致这种情况。

例如,考虑一个空数组。首先,我们尝试将一些新索引推送到数组中,而不进行任何特殊排序。一个很好的例子是以字符串作为键的数组。现在深入研究一个例子:

// Define an array
$arr = [];

// Adding unsorted keys
$arr["I"] = "we";
$arr["you"] = "you";
$arr["he"] = "they";

现在,我们有一个未排序的键数组(例如,“他”在“你”之后)。考虑相同的数组,但我们按字母顺序对它的键进行排序:

// Declare array
$alphabetArr = [];

// Adding alphabetical-sorted keys
$alphabetArr["I"] = "we";
$alphabetArr["he"] = "they";
$alphabetArr["you"] = "you";

提示:您可以使用键对数组进行排序 排序() 功能。

现在您有了另一个数组,其键排序与第一个数组不同。因此,我们将比较它们:

$arr == $alphabetArr; // true
$arr === $alphabetArr; // false

笔记:这可能是显而易见的,但比较两个 不同的 使用严格比较的数组总是会产生结果 false. 。但是,两个任意数组可以使用以下方法相等 === 或不。

你会说:“这种差异可以忽略不计”。然后我说这是一个区别,应该考虑并且可能随时发生。如上所述,对数组中的键进行排序就是一个很好的例子。

对象

记住, 两个不同的对象永远不会严格相等. 。这些例子会有所帮助:

$stdClass1 = new stdClass();
$stdClass2 = new stdClass();
$clonedStdClass1 = clone $stdClass1;

// Comparing
$stdClass1 == $stdClass2; // true
$stdClass1 === $stdClass2; // false
$stdClass1 == $clonedStdClass1; // true
$stdClass1 === $clonedStdClass1; // false

笔记:将一个对象分配给另一个变量不会创建副本 - 相反,它会创建对与该对象相同的内存位置的引用。 看这里.

笔记:从 PHP7 开始, 匿名类 加入。从结果来看,两者没有区别 new class {}new stdClass() 在上面的测试中。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top