khaverim
khaverim

Reputation: 3544

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 protected]", "[email protected]", "[email protected]");
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) ?

Upvotes: 0

Views: 90

Answers (3)

Hugo Dozois
Hugo Dozois

Reputation: 8420

Just make your if clause use the end function:

if ($email == end($sendto))

Upvotes: 1

Michael Best
Michael Best

Reputation: 16688

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

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

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

No need.

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

Upvotes: 5

Related Questions