PHP - Check if two arrays are equal

后端 未结 15 1945
说谎
说谎 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

    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; 
    

提交回复
热议问题