Search code examples
phparraysarray-difference

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.


Solution

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