0

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: 
2
  • Feel free to edit the title, i had a had a hard time formulating the question. I will stay online until it is answered so feel free to ask for more details. Commented Dec 15, 2015 at 10:16
  • Simply use array_diff function of PHP. Check This Commented Dec 15, 2015 at 10:25

3 Answers 3

2

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 )
Sign up to request clarification or add additional context in comments.

1 Comment

I replaced the example from the documentation with your numbers. Better?
1
$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);

Comments

1

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.