note 43114 modified in function.array-unique by vrana
| From: | vrana@php.net | Date: | Tue, 17 Aug 2004 14:50:16 +0000 |
| Subject: | note 43114 modified in function.array-unique by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-79970@lists.php.net to get a copy of this message | ||
The following is an efficient, adaptable implementation of array_unique which always retains the
first key having a given value:
<?php
function array_unique2(&$aray) {
$aHash = array();
foreach ($aray as $key => &$val) if (@$aHash[$val]++) unset ($aray[$key]);
}
?>
It is also adaptable to multi dimensional arrays. For example, if your array is a sequence of
(multidimensional) points, then in place of @$aHash[$val]++ you could use
@$aHash[implode("X",$val)]++
If you want to not have holes in your array, you can do an array_merge($aray) at the end.
Csaba Gabor
--was--
The following is an efficient, adaptable implementation of array_unique which always retains the
first key having a given value:
function array_unique2(&$aray) {
$aHash = array();
foreach ($aray as $key => &$val) if (@$aHash[$val]++) unset ($aray[$key]);
}
It is also adaptable to multi dimensional arrays. For example, if your array is a sequence of
(multidimensional) points, then in place of @$aHash[$val]++ you could use
@$aHash[implode("X",$val)]++
If you want to not have holes in your array, you can do an array_merge($aray) at the end.
Csaba Gabor
http://php.net/manual/en/function.array-unique.php