namht1st's avatar

Check duplicate in an array and return duplicate positions

Hi. I'm using Laravel Excel to upload an excel file then insert to database but first i want to check if the data given in file are duplicate or not. How can i check if the username duplicate and receive the position of duplicate row :D Thanks in advance

0 likes
3 replies
stefanbauer's avatar

I don't know Laravel Excel, but i assume you have the excel/csv date in some kind of array? If so, you can easily filter out the duplicates? There are several possibilities depending on your data structure. array_unique, loop while skipping the already added rows, etc. (with the last solution you would also get the affected rows).. why do you need the position of the duplicate row?

namht1st's avatar

@StefanBauer I got the username and email arrays of users from excel file. I know i can use array_unique to check duplicate in each arrays but i want to show where the duplicate position to users so they can fix it.

for ($i = 0; $i < count($users) - 1; $i ++)
            {
                
                for ($j = $i + 1; $j < count($users); $j ++)
                {
                    if ($users[$i]['ten_tai_khoan'] == $users[$j]['ten_tai_khoan'])
                    {
                        $errors_username[] = $i ."-" .$j;

                    }
                    if ($users[$i]['email'] == $users[$j]['email'])
                    {
                        $errors_emails[] = $i ."-" .$j;
                    }
                }
                
            }

This works but i want to show all duplicate positions and reduce the loop to increase performance

stefanbauer's avatar
Level 26

Just use the first loop. Create an array like $processedUsernames = []; and fill the array in each loop with the username you processed. Before doing that, check if the username you are processing is in the $processedUsernames array. If so, you have the record (and therefore the row) which is a duplicate. You can create a new array, where you save informations about the duplicates. Like $duplicates[] = $users[$i]; or something..

1 like

Please or to participate in this conversation.