You will need to make your function case insensitive to get the "Hello" => "hello" result you are looking for, try this method:
$arr = array[1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U'];
// Convert every value to uppercase, and remove duplicate values
$withoutDuplicates = array_unique[array_map["strtoupper", $arr]];
// The difference in the original array, and the $withoutDuplicates array
// will be the duplicate values
$duplicates = array_diff[$arr, $withoutDuplicates];
print_r[$duplicates];
Output is:
Array
[
[3] => Hello
[4] => hello
]
Edit by @AlixAxel:
This answer is very misleading. It only works in this specific condition. This counter-example:
$arr = array[1=>'1233',2=>'12334',3 =>'Hello' ,4=>'HELLO', 5=>'U'];
Fails miserably. Also, this is not the way to keep duplicates:
array_diff[$arr, array_unique[$arr]];
Since one of the duplicated values will be in array_unique
, and then chopped off by array_diff
.
Edit by @RyanDay:
So look at @Srikanth's or @Bucabay's answer, which work for all cases [look for case insensitive in Bucabay's], not just the test data specified in the question.
[PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8]
array_unique — Removes duplicate values from an array
Description
array_unique[array $array
, int $flags
= SORT_STRING
]: array
Note that keys are preserved. If
multiple elements compare equal under the given flags
, then the key and value of the first equal element will be retained.
Note: Two elements are considered equal if and only if
[string] $elem1 === [string] $elem2
i.e. when the string representation is the same, the first element will be used.
Parameters
array
The input array.
flags
The
optional second parameter flags
may be used to modify the sorting behavior using these values:
Sorting type flags:
-
SORT_REGULAR
- compare items normally [don't change types] -
SORT_NUMERIC
- compare items numerically -
SORT_STRING
- compare items as strings -
SORT_LOCALE_STRING
- compare items as strings, based on the current locale.
Return Values
Returns the filtered array.
Changelog
7.2.0 | If flags is SORT_STRING , formerly array has been copied and non-unique elements have been removed [without packing the array afterwards], but now a new array is built by adding the unique elements. This can result in different numeric indexes.
|
Examples
Example #1 array_unique[] example
The above example will output:
Array [ [a] => green [0] => red [1] => blue ]
Example #2 array_unique[] and types
The above example will output:
array[2] { [0] => int[4] [2] => string[1] "3" }
Notes
Note: Note that array_unique[] is not intended to work on multi dimensional arrays.
Ghanshyam Katriya[anshkatriya at gmail] ¶
7 years ago
Create multidimensional array unique for any single key index.
e.g I want to create multi dimentional unique array for specific code
Code :
My array is like this,
You can make it unique for any field like id, name or num.
something like this,
I have develop this function for same :
Now, call this function anywhere from your code,
Output will be like this :
falundir at gmail dot com ¶
4 years ago
I find it odd that there is no version of this function which allows you to use a comparator callable in order to determine items equality [like array_udiff and array_uintersect]. So, here's my version for you:
And here is a test code:
stoff@ ¶
5 years ago
In reply to performance tests array_unique vs foreach.
In PHP7 there were significant changes to Packed and Immutable arrays resulting in the performance difference to drop considerably. Here is the same test on php7.1 here;
//sandbox.onlinephpfunctions.com/code/2a9e986690ef8505490489581c1c0e70f20d26d1
$max = 770000; //large enough number within memory allocation
$arr = range[1,$max,3];
$arr2 = range[1,$max,2];
$arr = array_merge[$arr,$arr2];
$time = -microtime[true];
$res1 = array_unique[$arr];
$time += microtime[true];
echo "deduped to ".count[$res1]." in ".$time;
// deduped to 513333 in 1.0876770019531
$time = -microtime[true];
$res2 = array[];
foreach[$arr as $key=>$val] {
$res2[$val] = true;
}
$res2 = array_keys[$res2];
$time += microtime[true];
echo "
deduped to ".count[$res2]." in ".$time;
// deduped to 513333 in 0.054931879043579
Anonymous ¶
12 years ago
It's often faster to use a foreache and array_keys than array_unique:
Fabiano ¶
4 years ago
As for PHP 7.1.12, this is the comparison between array_keys[array_flip[]], array_flip[array_flip[]], for each elimination and array_unique. The array_keys[array_flip[]] is the fastest method to remove duplication values from a single dimension array:
mnbayazit ¶
14 years ago
Case insensitive; will keep first encountered value.
keneks at gmail dot com ¶
15 years ago
Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.
It simply compares the number of elements between the original array and the array_uniqued array.
contact at evoweb dot fr ¶
1 year ago
Here is a solution to make unique values keeping empty values for an array with keys :
calexandrepcjr at gmail dot com ¶
5 years ago
Following the Ghanshyam Katriya idea, but with an array of objects, where the $key is related to object propriety that you want to filter the uniqueness of array:
mostafatalebi at rocketmail dot com ¶
8 years ago
If you find the need to get a sorted array without it preserving the keys, use this code which has worked for me:
The above code returns an array which is both unique and sorted from zero.
regeda at inbox dot ru ¶
12 years ago
recursive array unique for multiarrays
sashasimkin at gmail dot com ¶
10 years ago
My object unique function:
And these code:
returns:
object[Test][1]
public 'pr0' => string 'string' [length=6]
public 'pr1' => string 'string1' [length=7]
public 'pr3' => string 'string2' [length=7]
agarcia at rsn dot com dot co ¶
16 years ago
This is a script for multi_dimensional arrays
Ludovico Grossi ¶
7 years ago
[Editor's note: please note that this will not work well with non-scalar values in the array. Array keys can not be arrays themselves, nor streams, resources, etc. Flipping the array causes a change in key-name]
You can do a super fast version of array_unique directly in PHP, even faster than the other solution posted in the comments!
Compared to the built in function it is 20x faster! [2x faster than the solution in the comments].
This works faster for small and big arrays.
quecoder at gmail ¶
14 years ago
another method to get unique values is :
Output:
Array [ [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f ]
subhrajyoti dot de007 at gmail dot com ¶
4 years ago
Simple and clean way to get duplicate entries removed from a multidimensional array.
jusvalceanu - SPAM at SPAM - yahoo dot com ¶
13 years ago
so .... my problem was multidimensional sort.
Array $attribs is an array contaning arrays. Each array in the $attrib array consists in multiple fields [ex: name, lenght, price, etc.] to be more simpler in speech think that $attrib is the array resulted by a search sql query done by a visitator on your online shoopping website ... [so ... each array in the $attrib is a product :P] if you want to sort only the uniq results use the above or use this:
Have fun tweaking this ;]] i know you will ;]]
From Romania With Love
webmaster at jukkis dot net ¶
15 years ago
Another way to 'unique column' an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.
Example:
In addition, use array_merge[ $unique ] to reindex.
zoolyka at gmail dot com ¶
6 years ago
I found the simplest way to "unique" multidimensional arrays as follows:
As you can see "b" will be removed without any errors or notices.
amri [ at t] dhstudio dot eu ¶
12 years ago
I searched how to show only the de-duplicate elements from array, but failed.
Here is my solution:
Example:
Output:
Array
[
[4] => xyzzy
[12] => |
[16] => &
[21] => foobar
]
csaba at alum dot mit dot edu ¶
18 years ago
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:
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
Sbastien ¶
3 months ago
Because of PHP comparaisons modalities, you can never distinguish null from others falsy values.
Note the absorbing nature of true and false booleans in mix types array.