0

I am in a confusing situation, I have an array where I want the duplicates removed. e.g

$arr = [
0 => array:25 [
    "content" => "abc" //duplicate
  ]
  1 => array:25 [
    "content" => "def"
  ]
  2 => array:1 [
    "content" => "abc" //duplicate
  ]
]

Now, I use array filter like this trying to remove duplicate "abc"

$filtered = array_filter( $arr, function($item) use($arr)
{
    foreach($arr as $item1)
    {
        return $item1['content'] !== $item['content']
    }
} 

This will give me the $filtered variable to be

[
0 => array:25 [
    "content" => "def"
  ]
]

But, what I really want is

 [
    0 => array:25 [
        "content" => "abc"
      ]
    1 => array:25 [
        "content" => "def"
      ]
    ]

i.e Removing one instance of duplicate not all.

Dhiraj
  • 2,687
  • 2
  • 10
  • 34

1 Answers1

3

You should somehow keep track of already visited $item['content']:

$visited = [];
$filtered = array_filter(
    $arr, 
    function($item) use(&$visited) {
        if (!isset($visited[$item['content']])) {
            $visited[$item['content']] = 1;
            return true;
        }

        return false;
    }
);
u_mulder
  • 54,101
  • 5
  • 48
  • 64