简体   繁体   中英

Check array value exists in another associative array

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM