PHP - Check if two arrays are equal

后端 未结 15 2113
说谎
说谎 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 11:49

    One way: (implementing 'considered equal' for http://tools.ietf.org/html/rfc6902#section-4.6)

    This way allows associative arrays whose members are ordered differently - e.g. they'd be considered equal in every language but php :)

    // recursive ksort
    function rksort($a) {
      if (!is_array($a)) {
        return $a;
      }
      foreach (array_keys($a) as $key) {
        $a[$key] = ksort($a[$key]);
      }
      // SORT_STRING seems required, as otherwise
      // numeric indices (e.g. "0") aren't sorted.
      ksort($a, SORT_STRING);
      return $a;
    }
    
    
    // Per http://tools.ietf.org/html/rfc6902#section-4.6
    function considered_equal($a1, $a2) {
      return json_encode(rksort($a1)) === json_encode(rksort($a2));
    }
    

提交回复
热议问题