1

I have an array which is like this:

$x = array("15","15","18","18","18","18","12","12");

then I want to get the unique values, which results in an array with unique values but with keys not reordered. What should I do? I want to avoid putting it in a loop.

2 Answers2

1

My Suggestion is to use

array_values(array_unique($x)); 

In this way, your array is first cleaned of the duplicate values, and then this array is returned to the function and finally the array values returns a re-ordered array of the filtered array.

Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105
1

You can use array_values() to re-index the array:

$x = array("15","15","18","18","18","18","12","12");
$unique = array_values(array_unique($x));
print_r($unique);

You can also use the sort() function, as mario suggested in the comments:

$unique = array_unique($x);
sort($unique);
print_r($unique);

Both of these will output:

Array
(
    [0] => 15
    [1] => 18
    [2] => 12
)
Amal Murali
  • 75,622
  • 18
  • 128
  • 150