php array уникальные значения
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 ++;
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.
Уникальные значения массива
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Как вывести из массива уникальные значения?
Доброго времени суток, уважаемые. Подскажите нубу, как можно из массива вывести лишь оригинальные.
Как реализовать функцию, которая принимает и возвращает в массив уникальные значения из исходного массива
Объясните пожалуйста, как реализовать функцию uniq, которая принимает, как аргумент, массив, и.
Нужно получить все уникальные значения из поля MySQL
День добрый! Народ, подскажите, сложилась такая задача: нужно получить все уникальные значения из.
Вот что выдает print_r($maches)
Добавлено через 1 минуту
Получается нужно вытащить второй массив) сейчас попробую
Добавлено через 3 минуты
insideone, Спасибо помогло))) просто вытащил в array_unique($maches[1]) и все заработало)
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Как без array_unique удалить из одного массива все значения, которые совпадают с значениями второго массива
Всем привет, не подскажете как без array_unique удалить из одного массива все значения, которые.
Получить все уникальные значения массива
Есть таблица 4х4, в ней 16 значений, из них от 2 до 8 уникальны, а остальные дублируют эти.
array
(PHP 4, PHP 5, PHP 7, PHP 8)
array — Создаёт массив
Описание
Создаёт массив. Подробнее о массивах читайте в разделе Массивы.
Список параметров
Наличие завершающей запятой после последнего элемента массива, несмотря на некоторую необычность, является корректным синтаксисом.
Возвращаемые значения
Примеры
Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.
Пример #1 Пример использования array()
Пример #2 Автоматическая индексация с помощью array()
Результат выполнения данного примера:
Этот пример создаёт массив, нумерация которого начинается с 1.
Результат выполнения данного примера:
Как и в Perl, вы имеете доступ к значениям массива внутри двойных кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.
Пример #4 Доступ к массиву внутри двойных кавычек
Примечания
Смотрите также
User Contributed Notes 38 notes
As of PHP 5.4.x you can now use ‘short syntax arrays’ which eliminates the need of this function.
So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an label. So, with this function, if only a single array is passed to the function (i.e. «arrayToSelect($stateList)») then it will simply spit out a bunch of » » elements. On the other hand, if two arrays are passed to it, the second array becomes a «key» for translating the first array.
Here’s a further example:
$countryList = array(
‘CA’ => ‘Canada’,
‘US’ => ‘United States’);
$stateList[‘CA’] = array(
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘MB’ => ‘Manitoba’,
‘NB’ => ‘New Brunswick’,
‘NL’ => ‘Newfoundland/Labrador’,
‘NS’ => ‘Nova Scotia’,
‘NT’ => ‘Northwest Territories’,
‘NU’ => ‘Nunavut’,
‘ON’ => ‘Ontario’,
‘PE’ => ‘Prince Edward Island’,
‘QC’ => ‘Quebec’,
‘SK’ => ‘Saskatchewan’,
‘YT’ => ‘Yukon’);
$stateList[‘US’] = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’);
Php array уникальные значения
В этом разделе помещены уроки по PHP скриптам, которые Вы сможете использовать на своих ресурсах.
Фильтрация данных с помощью zend-filter
Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.
Контекстное экранирование с помощью zend-escaper
Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.
Подключение Zend модулей к Expressive
Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.
Совет: отправка информации в Google Analytics через API
Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.
Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
Совет: активация отображения всех ошибок в PHP
При поднятии PHP проекта на новом рабочем окружении могут возникнуть ошибки отображение которых изначально скрыто базовыми настройками. Это можно исправить, прописав несколько команд.
Агент
PHP парсер юзер агента с поддержкой Laravel, работающий на базе библиотеки Mobile Detect.