0

This custom function is comparing two arrays, but if the arrays are completely different, i´ll get the error "Undefined variable: c". How can i fix this?

function myIntersect($a, $b) {
    foreach ($a as $x) {
        $i = array_search($x, $b);
        if ($i !== false) {
            $c[] = $x;
            unset($b[$i]);
        }
    }
    return $c;
}

Results:

$arrayone = array("3", "2", "1", "2", "3");
$arraytwo = array("1", "2", "3", "2", "1");
$result = myIntersect($arrayone, $arraytwo);
print_r($result); // ["3", "2", "1", "2"]
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
blasthrop
  • 25
  • 5

1 Answers1

1

add this to your function now it will define an empty array else you can define as boolean false. $c=array();

function myIntersect($a, $b) {
    $c=array();//add this to your function now it will define an empty array else you can define as boolean false
    foreach ($a as $x) {
        $i = array_search($x, $b);
        if ($i !== false) {
            $c[] = $x;
            unset($b[$i]);
        }
    }
    return $c;
}
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42