Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore Duplicates in Foreach loop

Tags:

php

I have the following script that loops through form entries on my website.

However, I'd like to remove any duplicate entries (in this case, entries using the same email address).

So if my foreach loop finds a duplicate email address, it breaks the loop.

How do I achieve this using my script below?

foreach ($scouts as $participant) {
            $fname    = ucfirst($participant['2']);
            $lname    = ucfirst($participant['3']);
            $email    = $participant['5'];
            $html .= "\t<li><a href=>$fname $lname $email</a></li>\n";
    }
like image 835
michaelmcgurk Avatar asked Jan 29 '26 21:01

michaelmcgurk


1 Answers

Create another array to store email addresses we've already outputted, then on each iteration check we've not used that e-mail address.

$emails = array(); //array to store unique emails (the ones we've already used)
foreach ($scouts as $participant) {
    $fname    = ucfirst($participant['2']);
    $lname    = ucfirst($participant['3']);
    $email    = $participant['5'];
    if( in_array($email, $emails) ) { //If in array, skip iteration
       continue;
    }
    $html .= "\t<li><a href=>$fname $lname $email</a></li>\n";
    $emails[] = $email; //Add email to "used" emails array
}
like image 189
ʰᵈˑ Avatar answered Feb 01 '26 09:02

ʰᵈˑ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!