(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP
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 comparison behavior using these values:Comparison 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
Version | Description |
---|---|
7.2.0 |
If flags is SORT_STRING ,formerly array has been copied and non-uniqueelements 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
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
The above example will output:
Array ( [a] => green [0] => red [1] => blue )
Example #2 array_unique() and types
<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>
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) ¶
8 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,
<?php
$details = array(
0 => array("id"=>"1", "name"=>"Mike", "num"=>"9876543210"),
1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
2 => array("id"=>"1", "name"=>"Mathew", "num"=>"784581254"),
);
?>
You can make it unique for any field like id, name or num.
I have develop this function for same :
<?php
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach(
$array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
?>
Now, call this function anywhere from your code,
something like this,
<?php
$details = unique_multidim_array($details,'id');
?>
Output will be like this :
<?php
$details = array(
0 => array("id"=>"1","name"=>"Mike","num"=>"9876543210"),
1 => array("id"=>"2","name"=>"Carissa","num"=>"08548596258"),
);
?>
Mike D. — michal at euro-net.pl ¶
5 months ago
modified code originally posted by Ghanshyam Katriya(anshkatriya at gmail) [highest voted comment here].
1. In php 7.4 counter $i breaks the function. Removed completely (imo was waste of keystrokes anyway).
2. I added second return value - array of duplicates. So you can take both and compare them (I had to).
Example array (copy-paste from original post):
<?php
$details = array(
0 => array("id"=>"1", "name"=>"Mike", "num"=>"9876543210"),
1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
2 => array("id"=>"1", "name"=>"Mathew", "num"=>"784581254"),
);
?>
Function:
<?php
function unique_multidim_array($array, $key) : array {
$uniq_array = array();
$dup_array = array();
$key_array = array();
foreach(
$array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[] = $val[$key];
$uniq_array[] = $val;
/*
# 1st list to check:
# echo "ID or sth: " . $val['building_id'] . "; Something else: " . $val['nodes_name'] . (...) "n";
*/
} else {
$dup_array[] = $val;
/*
# 2nd list to check:
# echo "ID or sth: " . $val['building_id'] . "; Something else: " . $val['nodes_name'] . (...) "n";
*/
}
}
return array($uniq_array, $dup_array, /* $key_array */);
}
?>
Usage:
<?php
list($unique_addresses, $duplicates, /* $unique_keys */) = unique_multidim_array($details,'id');
?>
Then:
var_dump($unique_addresses);
or
var_dump($duplicates);
or foreach or whatever. Personally I just echo-ed 1st and then 2nd (both DOUBLE COMMENTED) list in function itself (then copied both to notepad++ and compared them - just to be 100% sure), but in case you want to do something else with it - enjoy :)
Plus - as a bonus - you also get an array of UNIQUE keys you searched for (just uncomment >$key_array< in both: function return and function call code).
From example array code returns:
var_dump($unique_addresses);
array(2) {
[0]=>
array(3) {
["id"]=>
string(1) "1"
["name"]=>
string(4) "Mike"
["num"]=>
string(10) "9876543210"
}
[1]=>
array(3) {
["id"]=>
string(1) "2"
["name"]=>
string(7) "Carissa"
["num"]=>
string(11) "08548596258"
}
}
var_dump($duplicates);
array(1) {
[0]=>
array(3) {
["id"]=>
string(1) "1"
["name"]=>
string(6) "Mathew"
["num"]=>
string(9) "784581254"
}
}
Plus keys, if you want.
P.S.: in my - practical - case of DB querying I got around 4k uniques and 15k dupes :)
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:
<?php
function array_uunique(array $array, callable $comparator): array {
$unique_array = [];
do {
$element = array_shift($array);
$unique_array[] = $element;$array = array_udiff(
$array,
[$element],
$comparator
);
} while (count($array) > 0);
return
$unique_array;
}
?>
And here is a test code:
<?php
class Foo {
public
$a;
public function
__construct(int $a) {
$this->a = $a;
}
}$array_of_objects = [new Foo(2), new Foo(1), new Foo(3), new Foo(2), new Foo(2), new Foo(1)];$comparator = function (Foo $foo1, Foo $foo2): int {
return $foo1->a <=> $foo2->a;
};var_dump(array_uunique($array_of_objects, $comparator)); // should output [Foo(2), Foo(1), Foo(3)]
?>
stoff@ ¶
6 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;
http://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 "<br />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:
<?php
$max
= 1000000;
$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 666667 in 32.300781965256
$time = -microtime(true);
$res2 = array();
foreach($arr as $key=>$val) {
$res2[$val] = true;
}
$res2 = array_keys($res2);
$time += microtime(true);
echo "<br />deduped to ".count($res2)." in ".$time;
// deduped to 666667 in 0.84372591972351
?>
Ray dot Paseur at SometimesUsesGmail dot com ¶
15 years ago
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:
<?phpfunction array_not_unique($raw_array) {
$dupes = array();
natcasesort($raw_array);
reset ($raw_array);$old_key = NULL;
$old_value = NULL;
foreach ($raw_array as $key => $value) {
if ($value === NULL) { continue; }
if ($old_value == $value) {
$dupes[$old_key] = $old_value;
$dupes[$key] = $value;
}
$old_value = $value;
$old_key = $key;
}
return $dupes;
}$raw_array = array();
$raw_array[1] = 'abc@xyz.com';
$raw_array[2] = 'def@xyz.com';
$raw_array[3] = 'ghi@xyz.com';
$raw_array[4] = 'abc@xyz.com'; // Duplicate$common_stuff = array_not_unique($raw_array);
var_dump($common_stuff);
?>
keneks at gmail dot com ¶
16 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.
<?php
function array_has_duplicates(array $array)
{
$uniq = array_unique($array);
return count($uniq) != count($array);
}
?>
mnbayazit ¶
15 years ago
Case insensitive; will keep first encountered value.
<?php
function array_iunique($array) {
$lowered = array_map('strtolower', $array);
return array_intersect_key($array, array_unique($lowered));
}
?>
Fabiano ¶
5 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:
<?php
$max
= 1000000;
$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
"<br>deduped to ".count($res1)." in ".$time;
// deduped to 666667 in 0.78185796737671
// memory used: 33558528$time = -microtime(true);
$res2 = array_flip(array_flip($arr));
$time += microtime(true);
echo
"<br><br>deduped to ".count($res2)." in ".$time;
// deduped to 666667 in 0.072191953659058
// memory used: 3774873$time = -microtime(true);
$res3 = array();
foreach($arr as $key=>$val) {
$res3[$val] = true;
}
$res3 = array_keys($res3);
$time += microtime(true);
echo
"<br /><br>deduped to ".count($res3)." in ".$time;
// deduped to 666667 in 0.095494985580444
// memory used: 33558528$time = -microtime(true);
$res4 = array_keys(array_flip($arr));
$time += microtime(true);
echo
"<br /><br>deduped to ".count($res4)." in ".$time;
// deduped to 666667 in 0.05807900428772
// memory used: 33558528
contact at evoweb dot fr ¶
2 years ago
Here is a solution to make unique values keeping empty values for an array with keys :
<?php
function array_unique_kempty($array) {
$values = array_unique($array);
$return = array_combine(array_keys($array), array_fill(0,count($array),null));
return array_merge($return,$values);
}$myArray = [
"test1" => "aaa",
"test2" => null,
"test3" => "aaa",
"test4" => "bbb",
"test5" => null,
"test6" => "ccc",
"test7" => "ddd",
"test8" => "ccc"
];
echo
"<pre>".print_r(array_unique_kempty($myArray),true)."</pre>";/*
Array
(
[test1] => aaa
[test2] =>
[test3] =>
[test4] => bbb
[test5] =>
[test6] => ccc
[test7] => ddd
[test8] =>
)
*/
?>
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:
<?php
function obj_multi_unique($obj, $key = false)
{
$totalObjs = count($obj);
if (is_array($obj) && $totalObjs > 0 && is_object($obj[0]) && ($key && !is_numeric($key))) {
for ($i = 0; $i < $totalObjs; $i++) {
if (isset($obj[$i])) {
for ($j = $i + 1; $j < $totalObjs; $j++) {
if (isset($obj[$j]) && $obj[$i]->{$key} === $obj[$j]->{$key}) {
unset($obj[$j]);
}
}
}
}
return array_values($obj);
} else {
throw new Exception('Invalid argument or your array of objects is empty');
}
}
?>
regeda at inbox dot ru ¶
13 years ago
recursive array unique for multiarrays
<?php
function super_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach (
$result as $key => $value)
{
if ( is_array($value) )
{
$result[$key] = super_unique($value);
}
}
return
$result;
}
?>
mostafatalebi at rocketmail dot com ¶
9 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:
<?php
$array
= array("hello", "fine", "good", "fine", "hello", "bye");
$get_sorted_unique_array = array_values(array_unique($array));
?>
The above code returns an array which is both unique and sorted from zero.
sashasimkin at gmail dot com ¶
11 years ago
My object unique function:
<?php
function object_unique( $obj ){
$objArray = (array) $obj;$objArray = array_intersect_assoc( array_unique( $objArray ), $objArray );
foreach(
$obj as $n => $f ) {
if( !array_key_exists( $n, $objArray ) ) unset( $obj->$n );
}
return
$obj;
}
?>
And these code:
<?php
class Test{
public $pr0 = 'string';
public $pr1 = 'string1';
public $pr2 = 'string';
public $pr3 = 'string2';
}$obj = new Test;var_dump( object_unique( $obj ) );
?>
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 ¶
17 years ago
This is a script for multi_dimensional arrays
<?php
function remove_dup($matriz) {
$aux_ini=array();
$entrega=array();
for($n=0;$n<count($matriz);$n++)
{
$aux_ini[]=serialize($matriz[$n]);
}
$mat=array_unique($aux_ini);
for($n=0;$n<count($matriz);$n++)
{
$entrega[]=unserialize($mat[$n]);
}
return
$entrega;
}
?>
quecoder at gmail ¶
14 years ago
another method to get unique values is :
<?php
$alpha=array('a','b','c','a','b','d','e','f','f');
$alpha= array_keys(array_count_values($alpha));
print_r($alpha);
?>
Output:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
jusvalceanu — SPAM at SPAM — yahoo dot com ¶
14 years ago
so .... my problem was multidimensional sort.
<?php
$new = array();
$exclude = array("");
for ($i = 0; $i<=count($attribs)-1; $i++) {
if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
}
?>
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:
<?php
/* Our Array of products */
$attribs[] = array(
"name" => "Test Product 1",
"length" => "42 cm",
"weight" => "0,5 kg",
"price" => "10 $",
"stock" => "100",
);
$attribs[] = array(
"name" => "Test Product 2",
"length" => "42 cm",
"weight" => "1,5 kg",
"price" => "10 $",
"stock" => "200",
);
/* The nice stuff */
$new = array();
$exclude = array("");
for ($i = 0; $i<=count($attribs)-1; $i++) {
if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
}
print_r($new); // $new is our sorted array
?>
Have fun tweaking this ;)) i know you will ;))
From Romania With Love
Ludovico Grossi ¶
8 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).
<?php
function superfast_array_unique($array) {
return array_keys(array_flip($array));
}
?>
This works faster for small and big arrays.
subhrajyoti dot de007 at gmail dot com ¶
4 years ago
Simple and clean way to get duplicate entries removed from a multidimensional array.
<?php
$multi_array = $multi_array [0];
$multi_array = array_unique($multi_array);
print_r($multi_array);
?>
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:
<?php
/* example object */
class myObj {
public $id;
public $value;
function __construct( $id, $value ) {
$this->id = $id;
$this->value = $value;
}
}/* callback function */
function uniquecol( $obj ) {
static $idlist = array();
if (
in_array( $obj->id, $idlist ) )
return false;$idlist[] = $obj->id;
return true;
}/* a couple of arrays with second array having an element with same id as the first */
$list = array( new myObj( 1, 1 ), new myObj( 2, 100 ) );
$list2 = array( new myObj( 1, 10 ), new myObj( 3, 100 ) );
$list3 = array_merge( $list, $list2 );$unique = array_filter( $list3, 'uniquecol' );
print_r( $list3 );
print_r( $unique );?>
In addition, use array_merge( $unique ) to reindex.
zoolyka at gmail dot com ¶
7 years ago
I found the simplest way to "unique" multidimensional arrays as follows:
<?php
$array
= array(
'a' => array(1, 2),
'b' => array(1, 2),
'c' => array(2, 2),
'd' => array(2, 1),
'e' => array(1, 1),
);$array = array_map('json_encode', $array);
$array = array_unique($array);
$array = array_map('json_decode', $array);print_r($array);?>
As you can see "b" will be removed without any errors or notices.
amri [ at t] dhstudio dot eu ¶
13 years ago
I searched how to show only the de-duplicate elements from array, but failed.
Here is my solution:
<?php
function arrayUniqueElements($array)
{
return array_unique(array_diff_assoc($array1,array_unique($array1)));
};
?>
Example:
<?php
$arr1 = array('foo', 'bar', 'xyzzy', '&', 'xyzzy',
'baz', 'bat', '|', 'xyzzy', 'plugh',
'xyzzy', 'foobar', '|', 'plonk', 'xyzzy',
'apples', '&', 'xyzzy', 'oranges', 'xyzzy',
'pears','foobar');
$result=arrayUniqueElements($arr1);
print_r($result);exit;
?>
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:
<?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
free dot smilesrg at gmail dot com ¶
6 months ago
$a = new StdClass();
$b = new StdClass();
var_dump(array_unique([$a, $b, $b, $a], SORT_REGULAR));
//array(1) {
// [0]=>
// object(stdClass)#1 (0) {
// }
//}
$a->name = 'One';
$b->name = 'Two';
var_dump(array_unique([$a, $b, $b, $a], SORT_REGULAR));
//array(2) {
// [0]=>
// object(stdClass)#1 (1) {
// ["name"]=>
// string(3) "One"
// }
// [1]=>
// object(stdClass)#2 (1) {
// ["name"]=>
// string(3) "Two"
// }
//}
Sbastien ¶
1 year 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.
<?php
$a
= [true, false, null, '', '0', '123', 0, 123];
foreach (['SORT_REGULAR', 'SORT_NUMERIC', 'SORT_STRING', 'SORT_LOCALE_STRING'] as $flag) {
$a_new = array_unique($a, constant($flag));
echo "{$flag} ==> ";
var_dump($a_new);
}/*
Gives :
SORT_REGULAR ==> array(2) {
[0]=> bool(true)
[1]=> bool(false)
}
SORT_NUMERIC ==> array(3) {
[0]=> bool(true)
[1]=> bool(false)
[5]=> string(3) "123"
}
SORT_STRING ==> array(4) {
[0]=> bool(true)
[1]=> bool(false)
[4]=> string(1) "0"
[5]=> string(3) "123"
}
SORT_LOCALE_STRING ==> array(4) {
[0]=> bool(true)
[1]=> bool(false)
[4]=> string(1) "0"
[5]=> string(3) "123"
}
*/
Victoire Nkolo at crinastudio.com ¶
2 months ago
<?php//removes duplicated objetcs from an array according to the property givenclass ArrayFilter
{
public static function
dedupe_array_of_objets(array $array, string $property) : array
{
$i = 0;
$filteredArray = array();
$keyArray = array();
foreach(
$array as $item) {
if (!in_array($item->$property, $keyArray)) {
$keyArray[$i] = $item->$property;
$filteredArray[$i] = $item;
}
$i++;
}
return $filteredArray;
}
}
tasiot ¶
6 months ago
array_unique is not compatible with php 8.1 enums because enums don't have a string representation yet (even the BackedEnum of string type…).
You get an error: "Object of class XXXX could not be converted to string."
So I wrote this function that creates a string representation of the enums and use the array keys to remove duplicates:
<?phpfunction array_unique_81(array $values): array
{
$unique = [];
foreach ($values as $value) {
if ($value instanceof UnitEnum) {
$key = 'e:' . get_class($value) . ':' . $value->name;
} else {
$key = 's:' . (string)$value;
}
$unique[$key] = $value;
}
return array_values($unique);
}?>
dirk dot avery a t gmail ¶
14 years ago
Although array_unique is not intended to work with multi-dimensional arrays, it does on 5.2.9. However, it does not for 5.2.5. Beware.
Dorphalsig ¶
14 years ago
I had a problem with array_unique and multidimensional arrays ... Maybe there's a better way to do this, but this will work for any dimensional arrays.
<?php
function arrayUnique($myArray)
{
if(!is_array($myArray))
return $myArray;
foreach (
$myArray as &$myvalue){
$myvalue=serialize($myvalue);
}
$myArray=array_unique($myArray);
foreach (
$myArray as &$myvalue){
$myvalue=unserialize($myvalue);
}
return
$myArray;
}
?>
PHP Expert ¶
15 years ago
Case insensitive for PHP v4.x and up.
<?php
function in_iarray($str, $a) {
foreach ($a as $v) {
if (strcasecmp($str, $v) == 0) {
return true;
}
}
return false;
}
function
array_iunique($a) {
$n = array();
foreach ($a as $k => $v) {
if (!in_iarray($v, $n)) {
$n[$k]=$v;
}
}
return $n;
}
$input = array("aAa","bBb","cCc","AaA","ccC","ccc","CCC","bBB","AAA","XXX");
$result = array_iunique($input);
print_r($result);
/*
Array
(
[0] => aAa
[1] => bBb
[2] => cCc
[9] => XXX
)
*/
?>
geuis dot teses at gmail dot com ¶
16 years ago
Here's the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.
<?php
// Fruits, vegetables, and other food:
$var = array('apple','banana','carrot','cat','dog','egg','eggplant','fish');
$var = array_values(array_unique($var));
?>
memandeemail at gmail dot com ¶
17 years ago
Problem:
I have loaded an array with the results of a database
query. The Fields are 'FirstName' and 'LastName'.
I would like to find a way to contactenate the two
fields, and then return only unique values for the
array. For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell
Solution:
<?php
/**
* The same thing than implode function, but return the keys so
*
* <code>
* $_GET = array('id' => '4587','with' => 'key');
* ...
* echo shared::implode_with_key('&',$_GET,'='); // Resultado: id=4587&with=key
* ...
* </code>
*
* @param string $glue Oque colocar entre as chave => valor
* @param array $pieces Valores
* @param string $hifen Separar chave da array do valor
* @return string
* @author memandeemail at gmail dot com
*/
function implode_with_key($glue = null, $pieces, $hifen = ',') {
$return = null;
foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
return substr($return,1);
}
/**
* Return unique values from a tree of values
*
* @param array $array_tree
* @return array
* @author memandeemail at gmail dot com
*/
function array_unique_tree($array_tree) {
$will_return = array(); $vtemp = array();
foreach ($array_tree as $tkey => $tvalue) $vtemp[$tkey] = implode_with_key('&',$tvalue,'=');
foreach (array_keys(array_unique($vtemp)) as $tvalue) $will_return[$tvalue] = $array_tree[$tvalue];
return $will_return;
}
$problem = array_fill(0,3,
array('FirstName' => 'John', 'LastName' => 'Smith')
);
$problem[] = array('FirstName' => 'Davi', 'LastName' => 'S. Mesquita');
$problem[] = array('FirstName' => 'John', 'LastName' => 'Tom');
print_r($problem);
print_r(array_unique_tree($problem));
?>
Performance-Optimized Solution
If you care about performance and micro-optimizations, check this one-liner:
function no_dupes(array $input_array) {
return count($input_array) === count(array_flip($input_array));
}
Description:
Function compares number of array elements in $input_array
with array_flip’ed elements. Values become keys and guess what — keys must be unique in associative arrays so not unique values are lost and final number of elements is lower than original.
Warning:
As noted in the manual, array keys can be only type of int
or string
so this is what you must have in original array values to compare, otherwise PHP will start casting with unexpected results. See https://3v4l.org/7bRXI for an example of this fringe-case failure mode.
Proof for an array with 10 million records:
- The top-voted solution by Jason McCreary: 14.187316179276s 🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌
- The accepted solution by Mike Sherov: 2.0736091136932s 🐌🐌
- This answer’s solution: 0.14155888557434s 🐌/10
Test case:
<?php
$elements = array_merge(range(1,10000000),[1]);
$time = microtime(true);
accepted_solution($elements);
echo 'Accepted solution: ', (microtime(true) - $time), 's', PHP_EOL;
$time = microtime(true);
most_voted_solution($elements);
echo 'Most voted solution: ', (microtime(true) - $time), 's', PHP_EOL;
$time = microtime(true);
this_answer_solution($elements);
echo 'This answer solution: ', (microtime(true) - $time), 's', PHP_EOL;
function accepted_solution($array){
$dupe_array = array();
foreach($array as $val){
// sorry, but I had to add below line to remove millions of notices
if(!isset($dupe_array[$val])){$dupe_array[$val]=0;}
if(++$dupe_array[$val] > 1){
return true;
}
}
return false;
}
function most_voted_solution($array) {
return count($array) !== count(array_unique($array));
}
function this_answer_solution(array $input_array) {
return count($input_array) === count(array_flip($input_array));
}
Notice that accepted solution might be faster in certain condition when not unique values are near the beginning of huge array.
If you need a solution that will work with an array of arrays (or any array values other than integers or strings) try this:
function return_dup( $arr ) {
$dups = array();
$temp = $arr;
foreach ( $arr as $key => $item ) {
unset( $temp[$key] );
if ( in_array( $item, $temp ) ) {
$dups[] = $item;
}
}
return $dups;
}
$arr = array(
array(
0 => 'A',
1 => 'B',
),
array(
0 => 'A',
1 => 'B',
),
array(
0 => 'C',
1 => 'D',
),
array(
0 => 'C',
1 => 'D',
),
array(
0 => 'E',
1 => 'F',
),
array(
0 => 'F',
1 => 'E',
),
array(
0 => 'Y',
1 => 'Z',
),
);
var_export( return_dup( $arr ) );
/*
array (
0 => array (
0 => 'A',
1 => 'B',
),
1 => array (
0 => 'C',
1 => 'D',
),
)
*/
Оказывается, очень частая задача в тестовых заданиях соискателей — это поиск дубля в массиве. В зависимости от нюансов конкретного задания, могут просить:
- найти все дубли или один единственный дубль;
- использовать в решении самый быстрый алгоритм;
- найти вообще все повторяющиеся варианты.
Я рассмотрю здесь частное решение (целых три варианта), которое вы подкрутите для своего случая. Это поиск единственного дубля в массиве чисел.
Итак, пусть $A — произвольный массив чисел. Напишем функцию, которая ищет близнеца или возвращает FALSE.
Скоростной вариант
Самый первый и самый быстрый вариант поиска — это положиться только на функции PHP без каких либо свои циклов и ветвлений.
function array_find_twins($A) { $N = array_flip(array_count_values($A)); return isset($N[2]) ? $N[2] : FALSE; } |
Мы посчитали число значений, а потом просто вывернули массив. Если дублей было несколько — останется только один. Если нужно другое число повторений — используйте другой ключ на выходе (не 2, а 3, 4..).
PHP гораздо быстрее работает внутри собственных откомпилированных функций, нежели с вашими алгоритмами, какими бы они не были гениальными.
Вариант с сортировкой
Здесь мы сортируем массив, чтобы потом «вручную» просканировать его и найти рядом стоящих близнецов.
Так мы обнаружим любое повторяющееся произвольное число раз значение (т.е. тройняшек, и т.д.)
function array_find_twins2($A) { sort($A, SORT_NUMERIC); $last = —1; foreach($A as $value) { if ($last == $value) { return $value; } $last = $value; } return FALSE; } |
Если по условиям задачи массив уже отсортирован, то sort() можно убрать. Останется сканер массива, быстродействие которого линейно зависит от размеров массива.
В среднем, этот вариант в 2-3 раза медленнее предыдущего (на диапазоне от 1к до 100 к элементов).
Перекладываем из одной корзины в другую
Самый тормозной, неэффективный из трех.
Мы перебираем вх. массив ($A), складывая элементы в другой ($B). Но если в нем ($B) уже есть искомое значение, то вуаля! мы нашли близнеца.
function array_find_twins3($A) { $B = array(); $last = —1; foreach($A as $value) { if (in_array($value, $B)) return $value; $B[] = $value; } return FALSE; } |
В некоторых случаях, такая конструкция бывает востребована. Например, когда вы должны провести какие вычисления с каждым элементом, а потом уже принимать решение об эквивалентности.
Этот вариант на 2 порядка хуже первого решения.
Если у вас есть другие варианты — присылайте :).
Данная запись опубликована в 20.06.2017 23:26 и размещена в PHP.
Вы можете перейти в конец страницы и оставить ваш комментарий.
The PHP array unique is a function that allows removing duplicate values from an array while returning an array of unique values only. This implies that the given function isn’t anything less than a system that allows only one entry for a particular id. Therefore, we created this article to help you filter out the repetitive values from an array.
Keep reading to create an identity check system that doesn’t allow multiple array entries based on repetitive values.
Contents
- What is PHP array_unique?
- – Coding Example
- Array_unique in PHP: Working With Associative Arrays
- – Coding Example for PHP array_unique With Associative Array
- PHP Array Unique Values: Multidimensional Array
- – Coding Example
- – Note:
- PHP Array Remove Duplicates: Only Repetitive Arrays
- – Coding Example
- – Note:
- Get Unique Values From Array: Using Array Functions
- – Coding Example for Using PHP Array Unique With Other Functions
- Conclusion
What is PHP array_unique?
The PHP array_unique function accepts an array, removes all its duplicate values, and returns the array. It would be beneficial to keep in mind that the keys of the unique values will be preserved. So, the given function is as easy to use as a customized filter paper that allows only the first-found unique values to pass through it.
Now, please have a look at its syntax: array_unique(array, flag). Here, the flag parameter is optional and its default value is set to “SORT_STRING,” which means that the array values will be compared as strings.
Also, you can use the following flags for customizing the comparison:
- SORT_REGULAR: It doesn’t change the data types of the array values
- SORT_NUMERICC: It changes the array values to integers before comparing them
- SORT_LOCALE_STRING: It compares the array values as strings according to the current locale
– Coding Example
For example, let’s assume that your program contains an array that might contain duplicate values. So, here you’ll use the array unique function to remove duplicates from array PHP like the code snippet given below:
<?php
// creating an array of animals
$animals = array(“Cat”,”Dog”,”Tiger”,”Lion”,”Cat”);
// using the PHP array_unique function and printing the unique array
print_r(array_unique($animals));
?>
The following output will be displayed on your browser:
Array ( [0] => Cat [1] => Dog [2] => Tiger [3] => Lion )
Array_unique in PHP: Working With Associative Arrays
Does the functioning of the PHP array unique function change when you use it with an associative array? Well, the stated function works the same way as discussed above and matches the array values before generating an array of unique values.
– Coding Example for PHP array_unique With Associative Array
For example, you have an associative array of fruits but there is a chance that the array might contain the same fruit names more than once. So, in this situation, you’ll use the PHP array unique function to get an array of unique fruit names.
Please refer to the following example code snippet of the PHP array unique function:
?php
// creating an array of fruits
$fruits = array(
“One” => “Mango”,
“Two” => “Apple”,
“Three” => “Strawberry”,
“Four” => “Pineapple”,
“Two” => “Apple”, // duplicate value
“Five” => “Mango”, // duplicate value
);
// using the PHP array_unique function and printing the unique array
print_r(array_unique($fruits));
?>
This is the output that you’ll get:
Array ( [One] => Mango [Two] => Apple [Three] => Strawberry [Four] => Pineapple )
PHP Array Unique Values: Multidimensional Array
Can the PHP array unique function help in dealing with duplication in multidimensional arrays? Actually, the PHP array unique function doesn’t work with the multidimensional arrays but still, there is an alternative to it. Creating a user-defined function can help you in removing duplicate arrays from the main array based on a particular key. However, remember that the keys of the original array won’t be preserved.
– Coding Example
For example, there might be a case in which you have a multidimensional array containing the details of the employees. Now, you want to remove the whole inner array if its id key has a duplicate value. So, you’ll create a custom function that accepts an array and a key. The custom function uses the foreach loop and the in_array() function to check the uniqueness of the particular key.
Now, take a look at this code snippet that’ll make the understanding of this example easier for you:
<?php
// creating an array of employee details
$emp = array(
array(“id” => 1,”Position” => “Manager”,”Date” => “01-June-2020”),
array(“id” => 2,”Position” => “IT Incharge”, “Date” => “02-July-2020”),
array(“id” => 3,”Position” => “Accountant”,”Date” => “02-July-2020”),
array(“id” => 1,”Position” => “HR”, “Date” => “03-June-2020”),
);
// creating a custom function
function multi_unique_array($arr, $key) {
$Myarray = array();
$i = 0;
$array_of_keys = array();
foreach($arr as $val) {
if (!in_array($val[$key], $array_of_keys)) {
$array_of_keys[$i] = $val[$key];
$Myarray[$i] = $val;
}
$i++;
}
return $Myarray;
}
// calling the custom function with array and id key
$unique = multi_unique_array($emp,”id”);
// printing the multidimensional array with unique ids
print_r($unique);
?>
You’ll get the result below after running the code above:
Array (
[0] => Array ( [id] => 1 [Position] => Manager [Date] => 01-June-2020 )
[1] => Array ( [id] => 2 [Position] => IT Incharge [Date] => 02-July-2020 )
[2] => Array ( [id] => 3 [Position] => Accountant [Date] => 02-July-2020 )
)
– Note:
It isn’t important to have a multidimensional array with named keys to use the above function. You can simply pass “0” as the second argument to remove all the inner arrays that contain even a single duplicate value.
PHP Array Remove Duplicates: Only Repetitive Arrays
Certainly, the inner arrays of a multidimensional array may not contain all the duplicate values. Moreover, there can be a situation when you don’t want to remove the inner arrays based on a single duplicate value as discussed in the above example.
In that case, would you like to check all the values of the inner arrays before removing them?
Then don’t worry; you can achieve it as well by making a few changes in the custom function created above.
– Coding Example
For example, let’s say you have a multidimensional array of students in which each inner array consists of two values representing the student id and subject. Here, a student can study multiple subjects. Moreover, the same subject can be chosen by different students. So, you want to remove only those inner arrays that are completely duplicated.
Please have a look at the example code snippet given below:
<?php
$student = array(
array(“std1″,”English”),
array(“std1″,”Physics”),
array(“std2″,”English”),
array(“std2″,”Chemistry”),
array(“std2″,”Physics”),
array(“std3″,”English”),
array(“std2″,”English”), // duplicate
array(“std3″,”Sociology”),
array(“std3″,”Sociology”), // duplicate
array(“std4″,”English”),
array(“std1″,”Physics”), // duplicate
array(“std4″,”Chemistry”)
);
// creating a custom function
function multi_unique($array) {
$Myarray = array();
$array3 = array();
foreach($array as $val) {
if (!in_array($val, $array3)) {
$array3[] = $val;
$Myarray[] = $val;
}
}
return $Myarray;
}
$res = multi_unique($student);
print_r($res);
?>
This will be the output displayed on the browser:
Array (
[0] => Array ( [0] => std1 [1] => English )
[1] => Array ( [0] => std1 [1] => Physics )
[2] => Array ( [0] => std2 [1] => English )
[3] => Array ( [0] => std2 [1] => Chemistry )
[4] => Array ( [0] => std2 [1] => Physics )
[5] => Array ( [0] => std3 [1] => English )
[6] => Array ( [0] => std3 [1] => Sociology )
[7] => Array ( [0] => std4 [1] => English )
[8] => Array ( [0] => std4 [1] => Chemistry )
)
– Note:
The custom function used in the above code snippet won’t preserve the keys of the original array. If you want to preserve the keys then try out the following method.
Get Unique Values From Array: Using Array Functions
Although the user-defined functions help in getting unique values from the multidimensional arrays, the perseverance of keys can be an important task as well. Hence, a combination of array functions such as array_intersect_key, PHP array_unique, and array_map can help in solving the issue. However, you won’t be able to remove the inner arrays based on a particular key by using the stated combination.
– Coding Example for Using PHP Array Unique With Other Functions
Working on the same scenario from the previous example, here is a code snippet that will help you in preserving keys:
<?php
$get_unique = array_intersect_key($student , array_unique(array_map(‘serialize’ , $student)));
print_r($get_unique);
?>
This will be the output:
Array (
[0] => Array ( [0] => std1 [1] => English )
[1] => Array ( [0] => std1 [1] => Physics )
[2] => Array ( [0] => std2 [1] => English )
[3] => Array ( [0] => std2 [1] => Chemistry )
[4] => Array ( [0] => std2 [1] => Physics )
[5] => Array ( [0] => std3 [1] => English )
[7] => Array ( [0] => std3 [1] => Sociology )
[9] => Array ( [0] => std4 [1] => English )
[11] => Array ( [0] => std4 [1] => Chemistry )
)
Conclusion
The PHP array unique function helps in getting unique values from both indexed and associative arrays. Moreover, it works with other array functions to deal with the duplication in multidimensional arrays. Although you have already learned enough about making arrays unique, here are a few important points to enhance your clarity regarding the topic:
- The PHP array unique function accepts an array and removes all the duplicate values from it while preserving the keys
- The PHP array unique returns an array with unique values
- You can use the optional flag parameter to change the type of the values before comparing them
- The default value for the flag parameter is set to SORT_STRING
- The PHP array unique function doesn’t work with multidimensional arrays
- You can create a user-defined function to remove duplication from multidimensional arrays based on a particular key
- A user-defined function can help in getting unique values from multidimensional arrays without considering the keys
- You can use the PHP array unique function along with the other array functions to get unique values from a multidimensional array while preserving the keys
Through our guide, now, you can instantly remove the duplicate values from arrays without any difficulty.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team