Forum Moderators: coopster
I was looking for a function to compare two arrays, but I don't found anything useful, so I written this function, if someone needs it.
Usage:
This function is recursive.
(array) $needle: This array will be searched in the haystack.
(array) $haystack: Source array.
(bool) $match_all: If you want to match all values or just the first correct match, default is true.
If both arrays are empty the return is false.
function array_compare($needle, $haystack, $match_all = true)
{
if (!is_array($needle) ¦¦ sizeof($haystack) > sizeof($needle))
{
return false;
}$count = 0;
$result = false;
foreach ($needle as $k => $v)
{
if (!isset($haystack[$k]))
{
if ($match_all)
{
return false;
}
continue;
}if (is_array($v))
{
$result = array_compare($v, $haystack[$k], $match_all);
}$result = ($haystack[$k] === $v) && (($match_all && (!$count ¦¦ $result)) ¦¦!$match_all) ¦¦ (!$match_all && $result);
$count++;
}return $result;
}
Example:
$a = array('a', 'b');
$b = array('a', 'c');$r1 = array_compare($b, $a); // false
$r2 = array_compare($b, $a, false); // true$a = array('a' => 'a', 'b' => 'c');
$b = array('a' => 'z', 'b' => 'c');$r1 = array_compare($b, $a); // false
$r2 = array_compare($b, $a, false); // true
Complex example:
$a = array(
'a' => array(
'aa' => array('bb' => array('a' => 'av', 'bsuu' => array(';' => 2, 'l' => 4)), 'zz' => 5, 'cc' => 9)
)
);$b = array(
'a' => array(
'aa' => array('bb' => array('a' => 'av', 'bsuu' => array(';' => 2, 'l' => 4)), 'zz' => 5, 'cc' => 9)
)
);$c = array_compare($b, $a);
var_dump($c);
[edited by: Psychopsia at 5:40 pm (utc) on Dec. 1, 2006]
$array1 = array(
'1' => 'one',
'2' => 'two',
'3' => 'three'
);
$array2 = array(
'1' => 'one',
'2' => 'two',
'3' => 'three'
);
if ($array1 == $array2) {
print 'TRUE';
} else {
print 'FALSE';
}
I hope you don't think I am picking on your here, Psychopsia, I'm not. I'm just pushing the discussion a little to see what we can discover!
In the following I can't use straight comparison, check if user can submit tickets, $a is decoded array from database for the current user:
$a = array(
'tickets' => array(
'search' => array(
'a' => true
),
'submit' => true,
'view' => array(
'self' => true,
'others' => true
)
)
);$b = array(
'tickets' => array(
'submit' => true
)
);if (array_compare($a, $b, false))
{
// Show button
}
Note: The function check the type of values
$result = ($haystack[$k] === $v)...
[edited by: Psychopsia at 8:55 pm (utc) on Dec. 1, 2006]