Php array_unique does not work as expected

I am trying to learn how to use array_unique, so I made some code examples and I did not 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 result "15263", but not 7. After several tests, I think that it stops monitoring how it finds the first duplicate. Is this what is supposed to happen?

+4
source share
2 answers

Reason for withdrawal $uniques-

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

Your array does not contain a key 5, but the for echo $uniques[$i];value is not held in a loop echo $uniques[5];. this is the reason the value is missing 7.

Try it,

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

instead

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

, array_values($uniques)

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

array_unique , $uniques for. foreach, :

$uniques = array_values(array_unique($array, SORT_REGULAR));
+6

Source: https://habr.com/ru/post/1526797/


All Articles