Friday, April 15, 2011

How does the equivalence operator work with arrays in PHP?

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)
From stackoverflow
  • 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

    SilentGhost : @jackie: in array values do not exist w/o index.
  • 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);
    
  • It's to be expected, that

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

    and

    array(1,2,3) == array(1,2,3)
    
  • 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 : 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?
  • 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 : you're welcome to accept my answer :)
  • 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.

0 comments:

Post a Comment