Rob
Rob

Reputation: 195

How to remove duplicates within the key of an array

Im making a php site and i'm trying to get rid of all duplicate values within the key array. So if i have for example 2 twice in the key array how would i remove one of them.

My array looks like this:

Array
{
    [class 1] => Array
      {
           [0] => 1
           [1] => 2
           [2] => 3
           [3] => 2
      }


    [class 2] => Array
      {
           [0] => 1
           [1] => 2
           [2] => 3
           [3] => 2
      }
}

and i want to remove the duplicates that occur throughout the entire array.

Array
{
    [class 1] => Array
      {
           [0] => 1
           [1] => 2
           [2] => 3
      }


    [class 2] => Array
      {
           [0] => 1
           [1] => 2
           [2] => 3
      }
}

I've had a look online but I can only find examples of how to remove duplicate keys. Perhaps this could be done with a foreach loop but im not sure. All help appreciated. Thanks.

Upvotes: 1

Views: 191

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Just use array_map to execute array_unique on each sub-array of the array:

$array = array_map('array_unique', $array);

Not necessary, but if you want to reorder the keys afterward then use array_values the same way:

$array = array_map('array_values', $array);

Upvotes: 4

Related Questions