Bryan
Bryan

Reputation: 3494

array_unique() not making the array unique

I am generating an array of numbers based on an equation then rounding to the nearest 100.

After that I want to get rid of duplicates, array_unique seemed like the natural choice for this situation, but is not working as intended.

I created a small sample to demonstrate this. The PHP code is as follows:

var_dump($amounts);
array_unique($amounts);
var_dump($amounts);

The result of which is:

array(6) {
  [0]=>
  float(200)
  [1]=>
  float(300)
  [2]=>
  float(300)
  [3]=>
  float(400)
  [4]=>
  float(500)
  [5]=>
  float(500)
}
array(6) {
  [0]=>
  float(200)
  [1]=>
  float(300)
  [2]=>
  float(300)
  [3]=>
  float(400)
  [4]=>
  float(500)
  [5]=>
  float(500)
}

Can someone shed some light on what is happening here please?

Upvotes: 0

Views: 98

Answers (1)

Mr. Llama
Mr. Llama

Reputation: 20899

array_unique does not modify the array by reference. You'll need to catch the returned value:

$amounts = array_unique($amounts);

Note: the keys of the returned array may no longer be contiguous. If you want to make them contiguous again then you should use array_values.

Example:

$amounts = array(100, 200, 200, 200, 300, 400);
var_dump($amounts);
array(6) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [2]=>
  int(200)
  [3]=>
  int(200)
  [4]=>
  int(300)
  [5]=>
  int(400)
}

// Make the array unique
$amounts = array_unique($amounts);
var_dump($amounts);
array(4) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [4]=>
  int(300) // Notice the gap, indexes 2 and 3 don't exist.
  [5]=>
  int(400)
}

// Make the keys contiguous
$amounts = array_values($amounts);
var_dump($amounts);
array(4) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [2]=>
  int(300)
  [3]=>
  int(400)
}

Upvotes: 5

Related Questions