Mister Verleg
Mister Verleg

Reputation: 4293

Return the values of one array, but exclude the values of the second array

I have the following two arrays: the 2 arrays

Question: How can i make a 3th array containing the values of the first one excluding the values of the second one?

Additional information:

The first one is named $checked, the second one is named $exclude. The values to be excluded are always stored in the second array. The arrays can change in length, values, and order.

So that in this case i get this result:

     Array ( [0] => 26 [1] => 28 [2] => 34 ) <-- array 3: 

Upvotes: 0

Views: 261

Answers (3)

Gerald Schneider
Gerald Schneider

Reputation: 17797

you can use array_diff():

$checked = array(26,28,34,39,41);
$exclude = array(39, 41);
$result = array_diff($checked, $exclude);
print_r($result);

Result:

Array ( [0] => 26 [1] => 28 [2] => 34 )

Upvotes: 2

KiwiJuicer
KiwiJuicer

Reputation: 1982

$checked = array(11, 26, 38, 13);
$excludeValues = array(26, 38);

foreach ($excludeValues as $exclude) {

    if ($key = array_search ( $exclude , $checked )) {
        unset($checked[$key]);
    }

}

print_r($checked);

Upvotes: 1

Perrykipkerrie
Perrykipkerrie

Reputation: 390

Loop through the first array, then check if the value is present in the second array, if not, add it the the third array. Or use the array_diff function as proposed by Uchiha.

foreach($array1 as $items){
    if(!in_array($array2,$item)){
        $array3[] = $item
    }
}

Upvotes: 1

Related Questions