| Newsgroups |
php.notes |
| Message-ID |
<[email protected]> |
This is a cleaner and more modern approach (PHP 7.4+ syntax).
<?php
$array1 = ['blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4];
$array2 = ['green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8];
$result = array_intersect_ukey($array1, $array2, fn($a, $b) => $a <=> $b);
var_dump($result);
?>
Explanation:
The comparison function fn($a, $b) => $a <=> $b uses the spaceship operator directly inside the array_intersect_ukey call.
The result will contain entries from $array1 whose keys also exist in $array2.
Output:
php
Copy
Edit
array(2) {
["blue"]=>
int(1)
["green"]=>
int(3)
}
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 103.103.124.167)
----
Manual Page -- https://php.net/manual/en/function.array-intersect-ukey.php
Edit -- https://main.php.net/note/edit/130375
Del: integrated -- https://main.php.net/note/delete/130375/integrated
Del: useless -- https://main.php.net/note/delete/130375/useless
Del: bad code -- https://main.php.net/note/delete/130375/bad+code
Del: spam -- https://main.php.net/note/delete/130375/spam
Del: non-english -- https://main.php.net/note/delete/130375/non-english
Del: in docs -- https://main.php.net/note/delete/130375/in+docs
Del: other reasons-- https://main.php.net/note/delete/130375
Reject -- https://main.php.net/note/reject/130375
Search -- https://main.php.net/manage/user-notes.php