The following will compare two (multilevel) arrays whose keys may be string or numeric, AND which may not be in order, AND which is set to case insensitive by default. Additionally, you can flag it so the 2nd array can have additional keys in it not in the 1st, and it still be OK/equal (a real-life-situation I think).
A bright person could add a function like striptags or whatnot, and enhance this - but this helps me in some coding so I thought the community might be able to use it.
Samuel
function array_equal($a, $b, $bCanExceedA=false, $lower=true){
/* created 2007-06-21 - compares two arrays loosely and returns true if they are equal; default = lower case
if "b can exceed a" = true, then the function will accept elements in b which are not in a. This means you must
KNOW that b would always equal or exceed a; the function will not return true if a exceed b - maybe someone can develop
this so that it would return the exceeding keys portion
*/
//lower case comparison
if($lower){
foreach($a as $n=>$v)$a[strtolower($n)]=
(is_array($v)?$v:($lower?strtolower($v):$v));
foreach($b as $n=>$v)$b[strtolower($n)]=
(is_array($v)?$v:($lower?strtolower($v):$v));
}
//easy outs
if( $bCanExceedA && count($a) >count($b))return false;
if(!$bCanExceedA && count($a)<>count($b))return false;
//compare keys and values
foreach($a as $n=>$v){
if(is_null($v) && is_null($b[$n])) continue;
if(!isset($b[$n])) return false;
if(is_array($v) XOR is_array($b[$n])) return false;
if(is_array($v) && !array_equal($v, $b[$n], $bCanExceedA, $lower)) return false;
if(is_array($v)) continue;
if($v != $b[$n]) return false;
}
return true;
}
$a=array(
0=>array(
'5'=>'test',
8=>'TEST',
'great'=>'ape'
),
2.00=>array(
apple=>'test',
'hello'=>'TEST',
'dolly'=>'ape'
)
);
$b=array(
'0'=>array(
'5'=>'test',
8=>'TEST',
'great'=>'ape'
),
2=>array(
apple=>'test',
'hello'=>'test',
'dolly'=>'ape',
name=>value
)
);
echo 'a:';
print_r($a);
echo 'b:';
print_r($b);
echo array_equal($a,$b,false);