<?php
$array = [
"one" => ["id" => 111, "name" => "Jhon"],
"two" => ["id" => 222, "name" => "Adam"],
"three" => ["id" => 111, "name" => "Mark"],
"four" => ["id" => 125, "name" => "Jhon"],
"five" => ["id" => 111, "name" => "Jhon"],
"six" => ["id" => 222, "name" => "Rock"],
];
// store added IDs
$added = [];
// filter array (need to pass $added as reference to be updated)
$output = array_filter($array, function($item) use (&$added)
{
// shortcut for readability
$id = $item['id'];
// Check if id already exists
if (isset($added[$id])) { return false; }
// add to reference
$added[$id] = true;
// add to final array
return true;
});
unset($added); // no longer needed.
var_dump($output);
- Output for 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.4, 8.3.6 - 8.3.25, 8.4.1 - 8.4.13
- array(3) {
["one"]=>
array(2) {
["id"]=>
int(111)
["name"]=>
string(4) "Jhon"
}
["two"]=>
array(2) {
["id"]=>
int(222)
["name"]=>
string(4) "Adam"
}
["four"]=>
array(2) {
["id"]=>
int(125)
["name"]=>
string(4) "Jhon"
}
}
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
array(3) {
["one"]=>
array(2) {
["id"]=>
int(111)
["name"]=>
string(4) "Jhon"
}
["two"]=>
array(2) {
["id"]=>
int(222)
["name"]=>
string(4) "Adam"
}
["four"]=>
array(2) {
["id"]=>
int(125)
["name"]=>
string(4) "Jhon"
}
}
preferences:
153.26 ms | 409 KiB | 5 Q