php array merge unique
array_merge
(PHP 4, PHP 5, PHP 7, PHP 8)
array_merge — Сливает один или большее количество массивов
Описание
Сливает элементы одного или большего количества массивов таким образом, что значения одного массива присоединяются к концу предыдущего. Результатом работы функции является новый массив.
Если входные массивы имеют одинаковые строковые ключи, тогда каждое последующее значение будет заменять предыдущее. Однако, если массивы имеют одинаковые числовые ключи, значение, упомянутое последним, не заменит исходное значение, а будет добавлено в конец массива.
В результирующем массиве значения исходного массива с числовыми ключами будут перенумерованы в возрастающем порядке, начиная с нуля.
Список параметров
Возвращаемые значения
Возвращает результирующий массив. Если вызывается без аргументов, возвращает пустой массив ( array ).
Список изменений
Версия | Описание |
---|---|
7.4.0 | Функция теперь может быть вызвана без каких-либо параметров. Ранее требовался хотя бы один параметр. |
Примеры
Пример #1 Пример использования array_merge()
Результат выполнения данного примера:
Пример #2 Простой пример использования array_merge()
Помните, что числовые ключи будут перенумерованы!
Если вы хотите дополнить первый массив элементами второго без перезаписи элементов первого массива и без переиндексации, используйте оператор объединения массивов + :
Ключи из первого массива будут сохранены. Если ключ массива существует в обоих массивах, то будет использован элемент из первого массива, а соответствующий элемент из второго массива будет проигнорирован.
Пример #3 Пример использования array_merge() с не массивами
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 2 notes
In some situations, the union operator ( + ) might be more useful to you than array_merge. The array_merge function does not preserve numeric key values. If you need to preserve the numeric keys, then using + will do that.
[ 0 ] = «zero» ;
$array1 [ 1 ] = «one» ;
$array2 [ 1 ] = «one» ;
$array2 [ 2 ] = «two» ;
$array2 [ 3 ] = «three» ;
//This will result in::
?>
Note the implicit «array_unique» that gets applied as well. In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.
array_unique
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
array_unique — Убирает повторяющиеся значения из массива
Описание
Принимает входной массив array и возвращает новый массив без повторяющихся значений.
Обратите внимание, что ключи сохранятся. Если в соответствии с заданными flags несколько элементов определяются как идентичные, то будут сохранены ключ и значение первого такого элемента.
Список параметров
Можно использовать необязательный второй параметр flags для изменения поведения сортировки с помощью следующих значений:
Возвращаемые значения
Возвращает отфильтрованный массив.
Список изменений
Примеры
Пример #1 Пример использования array_unique()
Результат выполнения данного примера:
Пример #2 array_unique() и типы:
Результат выполнения данного примера:
Примечания
Замечание: Обратите внимание, что array_unique() не предназначена для работы с многомерными массивами.
Смотрите также
User Contributed Notes 41 notes
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,
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);
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:
$array_of_objects = [new Foo ( 2 ), new Foo ( 1 ), new Foo ( 3 ), new Foo ( 2 ), new Foo ( 2 ), new Foo ( 1 )];
It’s often faster to use a foreache and array_keys than array_unique:
For people looking at the flip flip method for getting unique values in a simple array. This is the absolute fastest method:
This tested on several different machines with 100000 random arrays. All machines used a version of PHP5.
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:
$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
Case insensitive; will keep first encountered value.
Simple and clean way to get duplicate entries removed from a multidimensional array.
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.
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:
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.
recursive array unique for multiarrays
This is a script for multi_dimensional arrays
My object unique function:
another method to get unique values is :
?>
Have fun tweaking this ;)) i know you will ;))
From Romania With Love
Another form to make an array unique (manual):
Array
(
[0] => Array
(
[0] => 40665
[1] => 40665
[2] => 40665
[3] => 40665
[4] => 40666
[5] => 40666
[6] => 40666
[7] => 40666
[8] => 40667
[9] => 40667
[10] => 40667
[11] => 40667
[12] => 40667
[13] => 40668
[14] => 40668
[15] => 40668
[16] => 40668
[17] => 40668
[18] => 40669
[19] => 40669
[20] => 40670
[21] => 40670
[22] => 40670
[23] => 40670
[24] => 40671
[25] => 40671
[26] => 40671
[27] => 40671
[28] => 40671
)
[1] => Array
(
[0] => 40672
[1] => 40672
[2] => 40672
[3] => 40672
)
0
0 => 40665
4 => 40666
8 => 40667
13 => 40668
18 => 40669
20 => 40670
24 => 40671
saludos desde chile.
[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).
I found the simplest way to «unique» multidimensional arrays as follows:
?>
As you can see «b» will be removed without any errors or notices.
Here’s the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.
I searched how to show only the de-duplicate elements from array, but failed.
Here is my solution:
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
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.
Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth.
I hope that the function will help someone
# move to the next node
continue;
# increment depth level
$l ++;
PHP Unique Values from Column in Array
I have an array that is generated from a SQL query that I run. It looks like the following:
How can I get the unique values from the email column? I appreciate the help.
5 Answers 5
The best answer is :
Either filter it in your column using the DISTINCT method in MySQL, or use something like
Since PHP 5.5, a new function called array_column() is also available. You can use it following way:
Remove duplicates from array comparing a specific key
Consider the same array but id of 3rd index is different:
Now, both 1 & 4 have same values. So we want to remove any of them:
If you get the list sorted by email from SQL you can improve performance by looping through the array like Gareth does, but instead only compare current email address with the last inserted email address. Below is a code example for this:
Not the answer you’re looking for? Browse other questions tagged php arrays unique or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
array_merge_recursive
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
array_merge_recursive — Merge one or more arrays recursively
Description
array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.
Parameters
Variable list of arrays to recursively merge.
Return Values
Changelog
Version | Description |
---|---|
7.4.0 | This function can now be called without any parameter. Formerly, at least one parameter has been required. |
Examples
Example #1 array_merge_recursive() example
The above example will output:
See Also
User Contributed Notes 37 notes
I refactored the Daniel’s function and I got it:
This is a simple, three line approach.
In Addition to felix dot ospald at gmx dot de in my opinion there is no need to compare keys with type-casting, as a key always is changed into an integer if it could be an integer. Just try
$a = array(‘1’=>’1’);
echo gettype(key($a));
It will echo ‘integer’. So for having Integer-Keys simply appended instead of replaced, add the Line:
A Condition I used is:
elseif (is_null($v)) unset($arr[$k]);
And the last one: If you want to use this approach for more than 2 Arrays, simply use this:
I little bit improved daniel’s and gabriel’s contribution to behave more like original array_merge function to append numeric keys instead of overwriting them and added usefull option of specifying which elements to merge as you more often than not need to merge only specific part of array tree, and some parts of array just need to let overwrite previous. By specifying helper element mergeWithParent=true, that section of array will be merged, otherwise latter array part will override former. First level of array behave as classic array_merge.
This is my version of array_merge_recursive without overwriting numeric keys:
function array_merge_recursive_new () <
There are a lot of examples here for recursion that are meant to behave more like array_merge() but they don’t get it quite right or are fairly customised. I think this version is most similar, takes more than 2 arguments and can be renamed in one place:
*Any key only appearing in the right one will be ignored*
— as I didn’t need values appearing only in the right in my implementation, but if you want that you could make some fast fix.
If what you want is merge all values of your array that are arrays themselves to get a resulting array of depth one, then you’re more looking for array_flatten function.
Unfortunately I did not find such native function in php, here is the one I wrote:
Here is a fairly simple function that replaces while recursing.
$array2 = array(
‘liquids’ => array(
‘water’ => ‘hot’
, ‘milk’ => ‘wet’
)
);
Result 2 is:
Array
(
[liquids] => Array
(
[water] => Array
(
[0] => cold
[1] => fizzy
[2] => clean
)
Here’s my function to recursively merge two arrays with overwrites. Nice for merging configurations.
I’ve edit this version even a little bit more, so that the function does not override any values, but inserts them at a free key in the array:
$array1 = array(
100 => array(30),
200 => array(20, 30)
);
$array2 = array(
100 => array(40),
201 => array(60, 30)
);
Output with array_merge_recursive:
Array
(
[0] => Array
(
[0] => 30
)
)
This is not the result, I expect from a MERGE-Routine.
Output with the current function:
This is what I want 🙂
In this version the values are overwritten only if they are not an array. If the value is an array, its elements will be merged/overwritten:
// We walk through each arrays and put value in the results (without
// considering previous value).
$result = array();
An alternative solution where this function does not produce the desired output: Pass a custom recursive function to array_reduce():
For example (Using PHP 7 capabilities to create recursive anonymous function):
Sharing my code to reserve the numeric keys:
$merged = array_merge_recursive($merged, revise_keys($candidate));
>
walfs version is pretty good, but it always assumes we want numeric keys as numeric keys. There are possibilities where a numeric key is actually a string ‘123’
For that I modified the function so that the last argument is a true switch to turn keys can be numeric on. Default is that keys are all string.
Attention.
(used PHP 5.4. XAMPP)
Values with numeric keys are always appended. The index of the merge array is determined by the startindex of the first array. Value4s with numeric keys seems always appended.
If a key looks like an integer, array_merge_recursive will interpret the string as an number.
This recursive array merge function doesn’t renumber integer keys and appends new values to existing ones OR adds a new php array merge unique pair if the pair doesn’t exist.
Merging arrays recursively some problem about existing keys, so that i wrote the function above like this:
This recursive array merge function doesn’t renumber integer keys and appends new values to existing ones OR adds a new php array merge unique pair if the pair doesn’t exist.
Proper simplistic example:
Sometimes you need to modify an array with another one here is my approach to replace an array’s content recursively with delete opiton. Here i used «::delete::» as reserved word to delete items.
/**
* Merges any number of arrays of any dimensions, the later overwriting
* previous keys, unless the key is numeric, in whitch case, duplicated
* values will not be added.
*
* The arrays to be merged are passed as arguments to the function.
*
* @access public
* @return array Resulting array, once all have been merged
*/
function array_merge_replace_recursive () <
// Holds all the arrays passed
$params = & func_get_args ();
I’ve tried these array_merge_recursive functions without much success. Maybe it’s just me but they don’t seem to actually go more than one level deep? As with all things, its usually easier to write your own, which I did and it seems to work just the way I wanted. Anyways, my function hasn’t been tested extensively, but it’s a simple function, so in hopes that this might be useful to someone else I’m sharing.
Also, the PHP function array_merge_recursive() didn’t work for my purposes because it didn’t overwrite the values like I needed it to. You know how it works, it just turns it into an array with multiple values. not helpful if your code is expecting one string.
// STRATEGY
/*
Merge array1 and array2, overwriting 1st array values with 2nd array
values where they overlap. Use array1 as the base array and then add
in values from array2 as they exist.
Walk through each value in array2 and see if a value corresponds
in array1. If it does, overwrite with second array value. If it’s an
array, recursively execute this function and return the value. If it’s
a string, overwrite the value from array1 with the value from array2.
If a value exists in array2 that is not found in array1, add it to array1.
*/
This behavior also occurs if the value is the empty array.
In fact, in the above example, interchanging the empty array with
any and all occurences of NULL will yield the same result.
var_dump ( array_merge_recursive2 (array( ‘A’ => array( ‘A’ => 2 )), array( ‘A’ => array( ‘A’ => null ))));
/*
array(1) < ["A"]=>array(1) < ["A"]=>NULL > >
*/
This function tends to reindex arrays, which is not mentioned in the function description.
I just tried to run that function on a three dimensional array, containing errormessages.
The first dim. contains the severity of the error (‘warn’, ‘crit’) the second dim the linenumber (numerical) and the third one consists of errormessages
# Array printout:
Array
(
[ warn ] => Array // severity (associative)
(
[ 2 ] => Array // linenumber (numerical)
(
[ 0 ] => «Category does not exist»
[ 1 ] => «Manufacturer does not exist»
)
)
)
?>
If i now merge two or more of those arrays using array_merge_recursive(), the linenumbers are not conserved. Instead of, they are all renumbered, starting with 0.
Just thought anyone may want to know about that. 🙂
regards, smilingrasta
I ran into a fairly unique situation where array_merge_recursive ALMOST did what I wanted, but NOT QUITE. I read through all of the comments, and I didn’t find anything that really helped me. I saw a lot of functions submitted that were just trying to recreate array_replace_recursive. This is not that.
Take a look at the code and try it out. Hopefully it helps someone in need!
/** We can skip the rest of the loop */
continue;
>
Merging two arrays in php using array_merge function and creating merged array with unique elements
Now, lets assume, you are aware of basics of array as mentioned above. We will create two arrays as below,
Above code creates two arrays and initializes those to some values. These two arrays can be simple merged using “array_merge” API as below,
Here, note that we passed names of these two arrays and created third new array named “array_after_merging” and displayed the array using “print_r”. “array_merge” Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
The output after merging will look like as below,
Note here, that the second array has been appended as is to first array, and array_merge preserved the index of the arrays to display.
Creating array with unique values in elements
The output to this will be as below,
NOTE: here the final array will have only 12 elements, removing the duplicated 7 & 3 from element [13] and [14] from previously merged array
Using only values from the merged arrays / merging arrays without keys
As we seen above array_merge preserves and shows the keys / index’s of the array elements, but sometimes we only need values from the merged array, for this there is no ready “merge without keys” function, so we will create another new array from the merged array and use function “array_values” for getting only elements in new array as,