php array_unique not working as expected

mucle6 picture mucle6 · Feb 13, 2014 · Viewed 9.7k times · Source

I am trying to learn how to use array_unique, so I made some sample code and I didn't get what I expected.

$array[0] = 1;
$array[1] = 5;
$array[2] = 2;
$array[3] = 6;
$array[4] = 3;
$array[5] = 3;
$array[6] = 7;
$uniques = array_unique($array, SORT_REGULAR);
for($i = 0; $i < count($uniques); $i++)
    echo $uniques[$i];

For example this gives me the output of '15263' but not 7. After a few test I think that it stops looking after it finds the first duplicate. Is that what is supposed to happen?

Answer

Krish R picture Krish R · Feb 13, 2014

Reason for $uniques output is

 Array
(
    [0] => 1
    [1] => 5
    [2] => 2
    [3] => 6
    [4] => 3
    [6] => 7
)

Your array doesn't contain key 5, but in your for loop echo $uniques[$i]; not hold the value of echo $uniques[5];. that is the reason value 7 is missing.

Try this,

foreach($uniques as $unique){
   echo $unique;
}

instead of

 for($i = 0; $i < count($uniques); $i++)

OR, you can re-index the array using array_values($uniques) and use,

  $uniques = array_values($uniques);
  for($i = 0; $i < count($uniques); $i++)
   echo $uniques[$i];