php array unique key
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.
PHP Array Unique Key
PHP Array Unique Key: Sometimes we need to extract the keys (uniquely) from an array. PHP provides array_keys() function to find out the same. This tutorial has several examples on associative array, numeric array, and multi-dimensional array and their respective output.
PHP Array Unique Key: Sometimes we need to extract the keys (uniquely) from an array. PHP provides array_keys() function to find out the same. This tutorial has several examples on associative array, numeric array, and multi-dimensional array and their respective output.
PHP Array Unique Key
In PHP if we want to get all the keys then we can use array_keys() function. array_keys() function returns an array of all keys, it returns all the keys irrespective of its type (i.e. string or numeric)
General Description of array_key
PHP Unique Array Key Example 1:
echo «
Initially the values of \$array1 is:
» ;
echo «
After extracting the keys uniquely:
» ;
echo «
Initially the values of \$array1 is:
» ;
echo «
After extracting the keys uniquely:
» ;
After extracting the keys uniquely:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
echo «
Initially the values of \$array1 is:
» ;
echo «
After extracting the keys uniquely:
» ;
echo «
Initially the values of \$array1 is:
» ;
echo «
After extracting the keys uniquely:
» ;
echo «
Initially the values of \$array1 is:
» ;
echo «
After extracting the keys uniquely:
» ;
echo «
Initially the values of \$array1 is:
» ;
echo «
After extracting the keys uniquely:
» ;
echo «
Initially the values of \$array1 is:
» ;
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_keys
(PHP 4, PHP 5, PHP 7, PHP 8)
array_keys — Возвращает все или некоторое подмножество ключей массива
Описание
Список параметров
Массив, содержащий возвращаемые ключи.
Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.
Определяет использование строгой проверки на равенство (===) при поиске.
Возвращаемые значения
Примеры
Пример #1 Пример использования array_keys()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 28 notes
It’s worth noting that if you have keys that are long integer, such as ‘329462291595’, they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.
?>
will return on a 64 bits system:
but on a 32 bits system:
I hope it will save someone the huge headache I had 🙂
Here’s how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:
Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.
Invalid:
echo array_shift( array_keys( array(‘a’ => ‘apple’) ) );
But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:
echo array_shift( ( array_keys( array(‘a’ => ‘apple’) ) ) );
However I would expect in time the PHP team will modify the rules of parentheses.
There’s a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.
Here’s a way to find all the keys from a multidimensional array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.
NOTE: If the sub element isn’t an array, it will be ignore.
output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)
array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0
—-
expected to see:
dude dude dude
Sorry for my english.
I wrote a function to get keys of arrays recursivelly.
Here’s a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.
?>
Example usage (pseudo-database code):
= db_query ( ‘SELECT name, value FROM properties’ );
/* This will return an array like so:
/* Now this array looks like:
?>
I found this handy for using with json_encode and am using it for my project http://squidby.com
This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don?t have control of depths.
An alternative to RQuadling at GMail dot com’s array_remove() function:
The position of an element.
One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output «yes, we have bananas at position 0».
Hope this helps someone.
# array_keys() also return the key if it’s boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:
Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)
This function will extract keys from a multidimensional array
Array
(
[color] => Array
(
[1stcolor] => blue
[2ndcolor] => red
[3rdcolor] => green
)
[size] => Array
(
[0] => small
[1] => medium
[2] => large
)
Array
(
[0] => color
[1] => 1stcolor
[2] => 2ndcolor
[3] => 3rdcolor
[4] => size
[5] => 0
[6] => 1
[7] => 2
)
All the cool notes are gone from the site.
Here’s an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.
Simple ways to prefixing arrays;
[1] => Array
(
[product_id] => 2
[product_name] => Bar
)
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn’t find a function I came up with my own solution.
I didn’t find the propiest function to post to so I will post it here, hope you find it useful.
?>
You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string
A needed a function to find the keys which contain part of a string, not equalling a string.