PHP: Built-in function to check whether two Array values are equal ( Ignoring the Order)

后端 未结 7 884
刺人心
刺人心 2020-12-30 01:34

Is there a built-in function for PHP for me to check whether two arrays contain the same values ( order not important?).

For example, I want a function that returns

相关标签:
7条回答
  • 2020-12-30 02:04

    The best solution is to sort both array and then compare them:

    $a = array('4','5','2');
    $b = array('2','4','5');
    sort($a);
    sort($b);
    var_dump($a === $b);
    

    As a function:

    function array_equal($a, $b, $strict=false) {
        if (count($a) !== count($b)) {
            return false;
        }
        sort($a);
        sort($b);
        return ($strict && $a === $b) || $a == $b;
    }
    

    Here’s another algorithm looking for each element of A if it’s in B:

    function array_equal($a, $b, $strict=false) {
        if (count($a) !== count($b)) {
            return false;
        }
        foreach ($a as $val) {
            $key = array_search($val, $b, $strict);
            if ($key === false) {
                return false;
            }
            unset($b[$key]);
        }
        return true;
    }
    

    But that has a complexity of O(n^2). So you better use the sorting method.

    0 讨论(0)
提交回复
热议问题