Skip to content

Commit 15d5e40

Browse files
authored
Speed up Arr::unique (#52)
1 parent d8a1733 commit 15d5e40

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/Arr.php

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,24 @@ final class Arr
2828
public static function unique(array $array, bool $keepKeys = false): array
2929
{
3030
if ($keepKeys) {
31-
$array = \array_unique($array);
32-
} else {
33-
// This is faster version than the builtin array_unique().
34-
// http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip
35-
// http://php.net/manual/en/function.array-unique.php
36-
$array = \array_keys(\array_flip($array));
31+
// This is faster than the builtin array_unique().
32+
$uniqueArray = [];
33+
34+
foreach ($array as $key => $value) {
35+
if (isset($uniqueArray[$value])) {
36+
continue;
37+
}
38+
39+
$uniqueArray[$value] = $key;
40+
}
41+
42+
return \array_flip($uniqueArray);
3743
}
3844

39-
return $array;
45+
// This is faster version than the builtin array_unique().
46+
// http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip
47+
// http://php.net/manual/en/function.array-unique.php
48+
return \array_keys(\array_flip($array));
4049
}
4150

4251
/**

0 commit comments

Comments
 (0)