1

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.

1
  • the built-in functions won't do this. you'll have to loop on the main array, and do a array_unique() on each of the child arrays. Commented Apr 21, 2015 at 17:40

1 Answer 1

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.