0

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?

1 Answer 1

5

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am such a rookie. What a simple thing to slip my mind. Thank you.
The first one liner was sufficient, I'll accept in 5 more minutes. Thanks for the detail though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.