php array unique values
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.
PHP unique array by value?
I have an array in PHP that looks like this:
The two values in «name» are the same in this two items. I want to sort out duplicates like this.
How do I create an unique array by checking the «name» value?
6 Answers 6
Serialisation is very useful for simplifying the process of establishing the uniqueness of a hierarchical array. Use this one liner to retrieve an array containing only unique elements.
Please find this link useful, uses md5 hash to examine the duplicates:
Given that the keys on the array (0,1) do not seem to be significant a simple solution would be to use the value of the element referenced by ‘name’ as the key for the outer array:
. and if there is only one value other than the ‘name’ why bother with a nested array at all?
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_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 ++;
Get unique array values with PHP
The PHP function array_unique() allows you to create a new array which contains only the unique values from the original array. This post looks at some examples of using the array_unique function.
In the example below we will use an array which has been initialised with a few values as shown below:
The PHP function print_r() to display the values of the above array will output the following:
As you can see from the above example, there are several duplicated values in the array, and we want to remove all the duplicated values. This is easily done as shown in the example below:
The above code will output the following, having removed the duplicated values from the array, and now only containing unique array values:
The above example shows us the original array but with the duplicate values remove. Notice that the array keys [2] and [5] have been removed because they already contain values that featured in keys earlier in the array.
Using array_unique with an associative array
An associative array contains mixed values as the array keys, whereas the above examples use a zero based integer indexed array. The principle of the array_unique() function is the same for an associative array: any array elements with duplicated values will be completely removed from the array.
For the following example, we will use a similar array as the above, but defined with text values for the indexes and integers for the values (the exact content of the key and value do not really matter):
Running print_r on this array will show the following:
Naturally, the second occurance of ‘foo’ and ‘bar’ as array keys overwrites the previous declarations in the array declaration. We can see in the above example that both ‘bar’ and ‘baz’ contain the same value of 3. So running array_unique() and then print_r() on the above array will do this:
So using the PHP function array_unique() on an associative array works the same way as for a zero based integer indexed array: it makes the values of the array unique, and doesn’t care about the key of the array. The key and value are completly removed from the array.
Как использовать array unique для массива массивов?
у меня есть массив
Как вы можете видеть ключ 0 такая же как 1,3 и 4. И ключ 2 отличается от них всех.
при запуске функции array_unique на них остается только
есть идеи, почему array_unique работает не так, как ожидалось?
5 ответов
потому что array_unique сравнивает элементы с помощью сравнения строк. От docs:
вы можете сделать то, что вы хотите сделать используя следующее:
вот как это работает:
каждый элемент массива сериализуется. Этот будет уникальным на основе массива содержание.
array_intersect_key возьмем ключи от уникальных предметов из функция map / unique (поскольку ключи исходного массива сохранены) и pull они из твоего первоисточник матрица.
array_unique() поддерживает только многомерные массивы в PHP 5.2.9 и выше.
, вы можете создать хэш-массива и проверить его на уникальность.
вот улучшенная версия @ryeguy это:
во-первых, он не делает ненужных сериализации. Во-вторых, иногда атрибуты могут отличаться, даже если id один и тот же.
array_unique deosn не работает рекурсивно, поэтому он просто думает: «это все Array s, давайте убьем всех, кроме одного. поехали!»
быстрый ответ (TL;DR)
Подробный Ответ!—5—>
контекст
решение
example01 ;; DeveloperMarsher начинает с переменной данных tabluar, которая выглядит следующим образом
example01 ;; DeveloperMarsher может извлекать различные значения с помощью цикла foreach, который отслеживает увиденные значения