Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array based on second array

I have an array $data and it is required to be filtered based on another array $clr. I have done it by foreach and solved my purpose but I am looking for an optimum way like map or filter. What I have tried is:

$clr = [1, 2, 4, 6, 8, 13, 21];
$data = [2, 3, 8];

foreach($clr as $val)
{
    if(($key = array_search($val, $data)) !== false) unset($data[$key]);
}

print '<pre>';
print_r($data);

Any of your suggestion will be appreciated.

like image 935
Janie Avatar asked Feb 10 '26 15:02

Janie


1 Answers

You can use array_diff($data, $clr); live demo.

like image 56
LF00 Avatar answered Feb 12 '26 16:02

LF00