简体   繁体   中英

PHP - check if array keys of two arrays match

I am trying to check two arrays for a certain key. If the key in both arrays matches I want to get it returned.
Here is a small example:

$array1 = ['one', 'helpMe!!', 'danger', 'correctKey'];
$array2 = ['correctKey'];
$result = some_method($array1, $array2); //Should return the string 'correctKey'

Of course you just could iterate over $array1 and check if the key matches, but I want to use a simple function that PHP maybe already provides.

Iteration:

foreach ($array1 as $arrayKey) {
    if ($array2['correctKey'] === $arrayKey) {
        $result = $arrayKey;
    }
}

Thanks for your help!

您正在寻找array_intersect

$result = array_intersect($array1, $array2);

What you are looking for is array_intersect() :

$array1 = ['one', 'helpMe!!', 'danger', 'correctKey'];
$array2 = ['correctKey'];

$matches = array_intersect($array1, $array2)

If you are checking the common keys in two arrays, as specified in the title:

$arr1 = [...];
$arr2 = [...];

$result  = array_intersect(array_keys($arr1), array_keys($arr2));

Even simpler, just as pointed out by AbraCadaver , use this

$result  = array_intersect_key($arr1, $arr2));

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