tags:

views:

169

answers:

6

Code:

$arr = array( 10, 20, 30 );
$arr1 = array(
       1=>30,
       2=>20,
       0=>10
);
var_dump( $arr == $arr1 );

$a = array( 1, 2, 3);
$b = array(
       1=>2,
       2=>3,
       0=>1
 );
var_dump($a == $b);

This outputs:

bool(false)
bool(true)
+6  A: 

Two arrays will be considered equal if their corresponding values are the same.

In your first example you are comparing two arrays:

[10, 20, 30]
[10, 30, 20]

Obviously these are not the same, so it returns false. The second example though:

[1, 2, 3]
[1, 2, 3]

...are the same. Am I missing something here?


If you want to test if two arrays have the same members, see this question: Algorithm to tell if two arrays have identical members

If you just want to see they have the same totals, you can use array_sum

nickf
this is a equivalence operator it should consider only values and not the index , if it is an identity operator(===) then it should consider order as well
@jackie: in array values do not exist w/o index.
SilentGhost
+2  A: 

If you do not specify keys for array, php automatically selects numbers, starting with 0. Therefore, the following pairs of lines mean the same:

$arr = array(10,20,30);
$arr = array(0=>10,1=>20,2=>30);

$a = array(1,2,3);
$a = array(0=>1,1=>2,2=>3);
phihag
this is a equivalence operator it should consider only values and not the index , if it is an identity operator(===) then it should consider order as well
A: 

It's to be expected, that

array(10,20,30) != array(10,30,20)

and

array(1,2,3) == array(1,2,3)
vartec
A: 

Thats a very broad question, but in the case of an array, it compares on an index-by-index basis.

In your first block of code, $arr is not equal to $arr1 because 30 != 10 and 10!=30.

In the second block of code, you are specifying that at index 0, the value is 1. At index 1, the value is 2, and at index 2, the value is 3. Thus, you have the same array.

JoshJordan
this is a equivalence operator it should consider only values and not the index , if it is an identity operator(===) then it should consider order as well
Well, in PHP you cannot have an array value without an index. Are you saying that (1,2,3) and (3,2,1) are equivalent?
JoshJordan
A: 

Given some of your comments, I think it would be useful if you read up on array type in php. Mainly the fact that there is no key-less arrays.
And don't forget comparison operators as well.

SilentGhost
hey thanksit is very useful as got the difference between order and keys of an array
you're welcome to accept my answer :)
SilentGhost
A: 

th equality operator is === in php and within an array => is correct. also $arr !=$arr1 coz 20 !=30, 30!=20 as per you have assigned.

terrific