PHP - Check if two arrays are equal

后端 未结 15 1924
说谎
说谎 2020-11-22 11:26

I\'d like to check if two arrays are equal. I mean: same size, same index, same values. How can I do that?

Using !== as suggested by a user, I expect th

相关标签:
15条回答
  • 2020-11-22 12:04

    According to this page.

    NOTE: The accepted answer works for associative arrays, but it will not work as expected with indexed arrays (explained below). If you want to compare either of them, then use this solution. Also, this function may not works with multidimensional arrays (due to the nature of array_diff function).

    Testing two indexed arrays, which elements are in different order, using $a == $b or $a === $b fails, for example:

    <?php
        (array("x","y") == array("y","x")) === false;
    ?>
    

    That is because the above means:

    array(0 => "x", 1 => "y") vs. array(0 => "y", 1 => "x").

    To solve that issue, use:

    <?php
    function array_equal($a, $b) {
        return (
             is_array($a) 
             && is_array($b) 
             && count($a) == count($b) 
             && array_diff($a, $b) === array_diff($b, $a)
        );
    }
    ?>
    

    Comparing array sizes was added (suggested by super_ton) as it may improve speed.

    0 讨论(0)
  • 2020-11-22 12:04

    Syntax problem on your arrays

    $array1 = array(
        'a' => 'value1',
        'b' => 'value2',
        'c' => 'value3',
     );
    
    $array2 = array(
        'a' => 'value1',
        'b' => 'value2',
        'c' => 'value3',
     );
    
    $diff = array_diff($array1, $array2);
    
    var_dump($diff); 
    
    0 讨论(0)
  • 2020-11-22 12:04

    Use php function array_diff(array1, array2);

    It will return a the difference between arrays. If its empty then they're equal.

    example:

    $array1 = array(
        'a' => 'value1',
    
        'b' => 'value2',
    
        'c' => 'value3'
     );
    
    $array2 = array(
        'a' => 'value1',
    
        'b' => 'value2',
    
        'c' => 'value4'
     );
    
    $diff = array_diff(array1, array2);
    
    var_dump($diff); 
    
    //it will print array = (0 => ['c'] => 'value4' ) 
    

    Example 2:

    $array1 = array(
        'a' => 'value1',
    
        'b' => 'value2',
    
        'c' => 'value3',
     );
    
    $array2 = array(
        'a' => 'value1',
    
        'b' => 'value2',
    
        'c' => 'value3',
     );
    
    $diff = array_diff(array1, array2);
    
    var_dump($diff); 
    
    //it will print empty; 
    
    0 讨论(0)
提交回复
热议问题