简体   繁体   中英

comparing arrays in php and in javascript return 2 different values. Why?

Guys something is really bothering me.

In JavaScript - Arrays are objects, meaning each arrays is allocated with a piece of memory for that datatype.

So that makes sense when

arr1 = [1,2,3]
arr2 = [1,2,3]

arr1 == arr2 returns false

HOWEVER

In php that same scenario returns true.

Why is that the case.

Here is why this returns false in Javascript :

When you create these 2 arrays:

arr1 = [1,2,3];
arr2 = [1,2,3];

you instantiate 2 different Array objects see Array reference . So, even if they have the same elements, they are not the same object, so it returns false.

if you create only one object and copy the reference to another variable, like this:

var arr1 = [1,2,3];
var arr2 = arr1
(arr1 == arr2) //returns true

it will returns true because they have the reference to the same object([1,2,3]).

I think that you are familiar with OO, if is not the case, please take a look at this: Object Oriented Programming

So, if you need to compare if each element of an array is equal to another in the same index you use the native function every() as @Prafulla Kumas Sahu mentioned. every doc .

Here is a naive example of how you could compare if 2 arrays have the same elements using every() :

var arr1 = [1,2,3];
var arr2 = [1,2,3];

arr1.every(function(value, index){
    return value == arr2[index];
}); 
//returns true

In PHP there are extra native operators for Arrays in the PHP language, php docs . They can check:

  • $a + $b Union Union of $a and $b.
  • $a == $b Equality TRUE if $a and $b have the same key/value pairs.
  • $a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
  • $a != $b Inequality TRUE if $a is not equal to $b.
  • $a <> $b Inequality TRUE if $a is not equal to $b.
  • $a !== $b Non-identity TRUE if $a is not identical to $b.

So, it's false in javascript because the operator == check if the instance of an Array object has the same reference to another.

And it's true in PHP because there are extra operators for arrays, and the operator == check if two different arrays have the same pair value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM