Search code examples
phparraysemailindices

How to indicate the last indice in a PHP array?


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) ?


Solution

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

    $to = implode(', ', $sendto);