Check if two arrays have the same values

后端 未结 9 1403
既然无缘
既然无缘 2020-12-15 02:45
[2,5,3]    

[5,2,3]

They are equal because they have the same values, but not in the same order. Can I find out that without using a foreach loop

9条回答
  •  余生分开走
    2020-12-15 03:31

    As none of the given answers that are completely key-independent work with duplicated values (like [1,1,2] equals [1,2,2]) I've written my own.

    This variant does not work with multi-dimensional arrays. It does check whether two arrays contain the exactly same values, regardless of their keys and order without modifying any of the arguments.

    function array_equals(array $either, array $other) : bool {
        $copy = $either;
        foreach ($other as $element) {
            $key = array_search($element, $copy, true);
            if ($key === false) {
                return false;
            }
            unset($copy[$key]);
        }
        return empty($copy);
    }
    

    Although the question asked about a foreach-free variant, I couldn't find any solution that satisfied my requirements without a loop. Additionally most of the otherwise used functions use a loop internally too.

提交回复
热议问题