doutong1890
doutong1890
2018-03-27 14:06

我应该使用array_diff_assoc还是===?

已采纳

I'm trying to compare two arrays to see if they are sorted or not. What is the difference between array_diff_assoc and comparing two arrays with the === operator? Are they the same thing?

For example

$arr_a
$arr_b

array_diff_assoc($arr_a, $arr_b)

Is the same as

$arr_a === $arr_b

?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dtebrq0245 dtebrq0245 3年前

    Simple example tells us that these are different methods:

    $a = ['t' => 2, 'p' => 3];
    $b = ['p' => 3, 't' => 2];
    var_dump($a === $b); // false, arrays are not identical                
    var_dump(array_diff_assoc($a, $b));  
    // array(0) {} - means that there's no difference between these arrays
    // they have same keys with same values, but in different orders 
    // and for `===` order is important
    
    点赞 评论 复制链接分享
  • donh61500 donh61500 3年前

    There are couple of differences.

    array_diff_assoc return an array that contains element in a not found in b.

    $a = [ 1 => 'first' , 2 , 3];
    $b = [ 1 => 'first' , 2 , 4 , 3];
    var_dump(array_diff_assoc($a,$b) // [ 3 => 3 ] because in a element 3 key is 3 and in b element 3 is 4. 
    

    Also array_diff_assoc does not work with multidimensional array. For more information visit the documentation array_diff_assoc

    $a === $b return true or false based on key/value pair comparison in addition to the order of the element and it can work with multidimensional array. So if you need a true or false comparison use

    $a === $b // if order and type is important 
    $a == $b  // if order and type are not important
    1 === '1' // false 
    1 == '1'  //true
    

    For more information visit the documentation Array Operators

    点赞 评论 复制链接分享

相关推荐