Search code examples
phparrayspchart

PHP: duplicate value removal


I have 2 arrays with for example 1000 key's each, one holds a temperature value and the other the hour.

Example array temp:

[0] = 3.1
[1] = 4.3
[2] = 4.1
[3] = 5.1
[4] = 4.1

Example hour array:

[0] = 0
[1] = 1
[2] = 2
[3] = 3
[4] = 3

The problem with this is that when i combine these to arrays and plot this in for example pchart i have too many values on the X and it gets cluttered.
So what i need to to remove the duplicate hours and replace then with "NULL", so that the unneeded hours are not plotted on the x axis.
I want to keep the first hour in the array, the second to the end of the duplicates can be set to "NULL"

The hour output array should be:

[0] = 0
[1] = 1
[2] = 2
[3] = 3
[4] = NULL
etc.

Solution

  • Your array is sorted, so... how about this?

    $hours = array(0,1,2,3,3,4,4,5);
    $prev = -1;
    foreach ($hours as &$hour) {
      if ($prev === $hour) {
        $hour = NULL;
      }
      else {
        $prev = $hour;
      }
    }
    unset($hour);
    print_r($hours); // 0,1,2,3,NULL,4,NULL,5...