개발 꿀팁/PHP

[PHP] Removing duplicate values in arrays, Array_unique ()

Jammie 2018. 1. 16. 01:11
반응형

Arrays of data types can have multiple values at the same time.

So there are many functions that manipulate array type data.

What if you want to have only one of the many data values in the array that do not have duplicate values in php?


※ Creating an array with only PHP different values


You can do it by hand, but what if the array has 10 million values? This must be impossible ... You can also use foreach loops to remove the same value one at a time, but this is also not a simple code.


php provides a very useful array_unique () function for this purpose. Here's how to use it.



array_unique (array name)


Using this function, it is very easy to remove the intermediate value of the array.

Let's take a closer look at the example below using this function.



※ See example of array_unique() in php


For example, suppose you have a variable in the $ test array: This variable contains a number of duplicate values, so let's use this function array_unique () to delete duplicate values.


<?php

$test = array("1", 2", "2", "3", "4", "4", "5", "5", "5");

$test2 = array_unique($test);

?>


When this function is executed, the result value returned will be as follows.


print_r($test2);


[0] => 1

[1] => 2

[2] => 3

[3] => 4

[4] => 5


With this function, we can simply and easily get the $ test2 variable with the desired unique value. Let's take a look at another example. Below is an array with a value of type character.



<?php

$notUnique = array("abc", "def", "efg", "efg", "efg", "hij");

$uniqueOnly = array_unique($notUnique);

?>


So far we have seen how to have only one array value.


반응형