Search code examples
phparraysfindunique

How to find values which were found before inside multi array


i do have currently following problem. I have to check if the array contains the exact same values and if they were found before.

int(3) wasn´t found before so it is 0, int(8) wasn´t found before so it is 0, int(5) wasn´t found before so it is 0, int(8) was found before so it is 1, int(3) and int(8) was not found together so it is 0, and so on.

I already tried it with array_unique but that didn´t work as i wanted

For example:

array(7) {
  [2] => array(1) {
    [0] => int(3)
  }
  [3] => array(1) {
    [0] => int(8)
  }
  [4] => array(1) {
    [0] => int(5)
  }
  [5] => array(1) {
    [0] => int(8)
  }
  [6] => array(2) {
    [0] => int(3)
    [1] => int(8)
  }
  [7] => array(2) {
    [0] => int(2)
    [1] => int(5)
  }
  [8] => array(2) {
    [0] => int(3)
    [1] => int(8)
  }
}

it must look something like this

array(7) {
  [2] => array(1) {
    [0] => int(0)
  }
  [3] => array(1) {
    [0] => int(0)
  }
  [4] => array(1) {
    [0] => int(0)
  }
  [5] => array(1) {
    [0] => int(1)
  }
  [6] => array(1) {
    [0] => int(0)
  }
  [7] => array(1) {
    [0] => int(0)
  }
  [8] => array(1) {
    [0] => int(1)
  }
}

Solution

  • You could use array_map() and serialize():

    <?php
    
    $data = [
        2 => [
            3,
        ],
        3 => [
            8,
        ],
        4 => [
            5,
        ],
        5 => [
            8,
        ],
        6 => [
            3,
            8,
        ],
        7 => [
            2,
            5,
        ],
        8 => [
            3,
            8,
        ],
    ];
    
    $occurrences = [];
    
    $mapped = array_map(function (array $values) use (&$occurrences) {
        // create serialized representation of the values
        // which we can use as an index 
        $index = serialize($values);
    
        // haven't seen these values before
        if (!array_key_exists($index, $occurrences)) {
            $occurrences[$index] = 1;
    
            return 0;
        }
    
        // increase our counter
        $occurrences[$index]++;
    
        return $occurrences[$index] - 1;
    }, $data);
    
    var_dump($mapped);
    

    For reference, see:

    For an example, see: