Jason Corick Jason Corick - 5 months ago 24
PHP Question

PHP Group Compare

So basically I got 2 arrays of groups which I need to compare.
But it always returns 'FALSE', any idea?

function QuickGroupCompare()
{
$pre = '2,3,4';
$groupids = '10,5,6,3,4,2,18,1';

$l_Group = explode(",", $pre);
$m_Group = explode(",", $groupids);

foreach ($l_Group as $index => $i_x)
{
if ($i_x == $m_Group[$index])
return 'CORRECT';
}

return 'FALSE';
}
echo QuickGroupCompare();


Thanks!

Answer

If you want to simply determine whether one of the numbers in $a exists in $b you can use array_intersect:

function compare($a, $b)
{
    return !empty(array_intersect($a, $b));
}

Example:

var_dump(compare($l_Group, $m_Group));              // true
var_dump(compare($l_Group, explode(',', '6,7,8'))); // false

Convert the boolean result to 'CORRECT' or 'FALSE' after the function call, it's better to return a boolean in this case from the function itself:

$result = compare($a, $b);
echo $result ? 'CORRECT' : 'FALSE';