Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mikiobryant's avatar

Remove duplicates in associative array by larger date

Hello,

I'm using Maatswebsite/Excel 2.1, and loading csv data to array. CSV data has some duplicates inside it. I would like to remove duplicates in multidimensional associative array based on 4 keys as a unique identifier. When duplicates are found, I would like to take one that has larger date in "date" key.

Could someone help me out.

0 likes
1 reply
Mikiobryant's avatar
Mikiobryant
OP
Best Answer
Level 5

Hope this helps someone.

            $haystack = array(...); //some array
                        $needles = array('one', 'two', 'three', 'four'); //keys

                        foreach($haystack as $row){

                                $key=implode('',array_intersect_key($row,array_flip($needles))); //make key

                                if(!isset($result[$key])) //if doesn't exist new one
                                {
                                    $result[$key]=$row;
                                }
                                else //if exists compare dates
                                {
                                    $date = strtotime($result[$key]['date']);
                                    $compare = strtotime($row['date']);

                                    if ($date > $compare) {
                                        continue;
                                    }
                                    else
                                    {
                                        $result[$key] = $row;
                                    }
                                } 
                            }

Please or to participate in this conversation.