views:

68

answers:

3
$teams = array(1, 2, 3, 4, 5, 6, 7, 8);
$game1 = array(2, 4, 6, 8);
$game2 = array();

if teams[x] is not in game1 then insert into game2

for($i = 0; $i < count($teams); $i++){
    for($j = 0; $j < count($game1); $j++){
        if($teams[$i] == $game1[$j]){
            break;
        } else {
            array_push($game2, $teams[$i]);
        }
    }
}

for ($i = 0; $i < count($game2); $i++) {
    echo $game2[$i];
    echo ", ";
}

Im expecting the result to be:

1, 3, 5, 7,

However, im getting:

1, 1, 1, 1, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,

How can i improve this? Thanks

+5  A: 

Others have already answered on how to use array_diff.

Reason why your existing loop does not work:

    if($teams[$i] == $game1[$j]){
        // this is correct, if item is found..you don't add.
        break; 
    } else {
        // this is incorrect!! we cannot say at this point that its not present.
        // even if it's not present you need to add it just once. But now you are
        // adding once for every test.
        array_push($game2, $teams[$i]);
    }

You can use a flag to fix your existing code as:

for($i = 0; $i < count($teams); $i++){
    $found = false; // assume its not present.
    for($j = 0; $j < count($game1); $j++){
        if($teams[$i] == $game1[$j]){
            $found = true; // if present, set the flag and break.
            break;
        }
    }
    if(!$found) { // if flag is not set...add.
        array_push($game2, $teams[$i]);
    }
}
codaddict
thanks, im still be interested to know why my loop isnt working. Any ideas?
Jonny
+5  A: 

Your loop doesn't work because every time the element from $teams is not equal to the element from $game1, it adds the $teams element to $game2. That means each element is being added to $game2 multiple times.

Use array_diff instead:

// Find elements from 'teams' that are not present in 'game1'
$game2 = array_diff($teams, $game1);
Richard Fearn
+1  A: 

You can use PHP's array_diff():


$teams = array(1, 2, 3, 4, 5, 6, 7, 8);
$game1 = array(2, 4, 6, 8);
$game2 = array_diff($teams,$game1);

// $game2:
Array
(
    [0] => 1
    [2] => 3
    [4] => 5
    [6] => 7
)
Alec