0

I have two different arrays (say) array1 and array2. I want to check whether a value in array2 exists in array1.

Array1
(
    [0] => Array
    (
        [id] => 7
        [title] => Course1
    )
    [1] => Array
    (
         [id] => 8
         [title] => course2
    )
    [2] => Array
    (
        [id] => 9
        [title] => course3
    )
)

Array2
(
    [0] => 7
    [1] => 8
)

I used:

foreach ($array2 as $id) {
    $found = current(array_filter($array1, function($item) {
       return isset($item['id']) && ($id == $item['id']);
    }));
    print_r($found);
}

When I run this code it give the following error:

Undefined variable: id
6
  • 5
    stackoverflow.com/questions/24760004/… Commented Jan 3, 2017 at 11:07
  • What exactly are you trying to do? Can you update your question to show us exactly what you tried and what output you expect to get. Commented Jan 3, 2017 at 11:08
  • Not clear to understand Commented Jan 3, 2017 at 11:12
  • Mention your code you have try to do this logic Commented Jan 3, 2017 at 11:45
  • please see my updated ques @Krishan Patel Commented Jan 3, 2017 at 11:49

2 Answers 2

1

The reason for your error is that you are trying to use a variable within your anonymous function that is not available to it. Have a read of the relevant PHP documentation (esp. Example #3) to make sure you are clear on what I'm talking about.

In brief, your variable $id is declared in the parent scope of your closure (or anonymous function). In order for it to be available within your closure you must make it available via the use statement.

If you change the key line of your code to be:

$found = current(array_filter($array1, function($item) use ($id) {

your program should work as expected.

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

Comments

0

Here is simple code as per your question :

foreach($array2 as $id){

        return in_array($id, array_column($array1, 'id'));

}

Make sure this is a useful to you.

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.