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.

0

1 Answer 1

4

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

1 Comment

gorgeous solution, never though it this way, thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.