0

I have a simple mail() script that sends to multiple emails dynamically by seperating the emails with commas.

<?php

$sendto = array("email@gmail.com", "email@zoho.com", "email@mail.usf.edu");
foreach ($sendto as $email)
{
    if ($email is the last indice in the array..) // <-- here
        $to = $email;
    else
        $to = $email . ', ';
}

$subject = "test message";
$msg = "this is a test";

if (mail($to, $subject, $msg)) 
    echo "message sent";
else 
    echo "uh oh";
?>

How do I identify if (this is the last piece of data in my array) ?

khaverim
  • 3,386
  • 5
  • 36
  • 46

3 Answers3

5

No need.

$to = implode(', ', $sendto);
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

php includes implode or join which will work much better here:

$to = implode(', ', $sendto);
Michael Best
  • 16,623
  • 1
  • 37
  • 70
1

Just make your if clause use the end function:

if ($email == end($sendto))
Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58