5

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?

mucle6
  • 645
  • 1
  • 10
  • 24

2 Answers2

9

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];
Krish R
  • 22,583
  • 7
  • 50
  • 59
  • Your array value doesn't contain key `5`, thats why – Krish R Feb 13 '14 at 19:11
  • 4
    Why doesn't it contain `5`? That's the question that needs to be addressed. Here's the answer: It is because `array_unique()` preserves keys. [The documentation](http://php.net/array_unique) states: `Note that keys are preserved`. Since you're using a `for` loop which operates on the array on the basis of numeric indexes, a missing position in the array will mean that it will not get echoed. Had you [enabled error reporting](http://stackoverflow.com/a/6575502/1438393), you'd have seen an error message saying `Undefined offset`. – Amal Murali Feb 13 '14 at 19:14
8

Since array_unique preserves the keys, you can’t access the array $uniques properly with a for loop. Either use a foreach loop or change the seventh line of your code to:

$uniques = array_values(array_unique($array, SORT_REGULAR));
Sharanya Dutta
  • 3,981
  • 2
  • 17
  • 27
  • 2
    @mucle6: It is because the `$uniques` array keys are **not continuous**. You need to re-index it for the `for` loop to work: https://eval.in/101407 – Amal Murali Feb 13 '14 at 19:11
  • @AmalMurali Sorry, I had to write this answer in a hurry and leave StackOverflow immediately afterwards, so there was no scope to update my answer and make it more lucid/elaborate. Now I’m glad to see that the accepted answer and your comments have said all I had to say (and more than that, indeed). Thank you especially for the precious demo. – Sharanya Dutta Feb 14 '14 at 01:36