Compare two associative arrays regarding the order of keys

爱⌒轻易说出口 提交于 2019-12-12 15:16:54

问题


Suppose, we have 2 associative arrays:

<?php
$array1 = array(
    1 => 2,
    2 => 1,
);

$array2 = array(
    2 => 1,
    1 => 2,
);

They contain same elements, but in different order. I wanted to write a comparison function, that will give true only if:

  1. Arrays have the same key => value pairs.
  2. Order of pairs is the same.

So, I tried the following:

1 try

if ($array1 == $array2)
{
    print "equal\n";
}

Prints: equal

2 try

print count(array_diff_assoc($array1, $array1));

Prints: 0

My custom function

Then I created the following function:

function compare(&$array1, &$array2)
{
    $n1 = count($array1);
    $n2 = count($array2);
    if ($n1 == $n2)
    {
        $keys1 = array_keys($array1);
        $keys2 = array_keys($array2);
        for ($i = 0; $i < $n1; ++$i)
        {
            if ($keys1[$i] == $keys2[$i])
            {
                if ($array1[$keys1[$i]] != $array2[$keys2[$i]])
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        return true;
    }
    else
    {
        return false;
    }
}

This works correctly, but it won't work, when we want this strict comparison applied for nested arrays of arrays because of != operator in this if:

if ($array1[$keys1[$i]] != $array2[$keys2[$i]])
{
       return false;
}

This can be fixed, using a recursive function, switching by type of data. But this simplified version was ok for me.

Is there any standard solution for this type of comparison?


回答1:


As described under array operators, what you want is the === equality operator.

if ($array1 === $array2) {
    echo "same key pairs and same element order\n";
}



回答2:


can you try the this below one. which returns true if the key=>value and will be in any order otherwise returns false

$array1 = array(
1 => 2,
2 => 1);           
$array2 = array(
2 => 1,
1 => 2);

var_dump(compareArray($array1,$array2));

function compareArray ($array1, $array2)
{

foreach ($array1 as $key => $value)

{

if ($array2[$key] != $value)

 {


return false;
}

 }
return true;
 }


来源:https://stackoverflow.com/questions/17924178/compare-two-associative-arrays-regarding-the-order-of-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!