3

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.

4
  • 1
    array_diff Commented May 8, 2017 at 9:49
  • 1
    @SahilGulati should be $data = array_diff($data,$clr); you got the parameter order wrong Commented May 8, 2017 at 9:52
  • php.net/manual/en/function.array-map.php Commented May 8, 2017 at 9:53
  • you can use array_filter as well. have a look at 3v4l.org/i53Ma Commented May 8, 2017 at 9:57

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think $data should be first argument.

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.