如何指示 PHP 数组中的最后一个标记


How to indicate the last indice in a PHP array?

我有一个简单的mail()脚本,它通过用逗号分隔电子邮件来动态发送到多封电子邮件。

<?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";
?>

如何识别是否(这是我数组中的最后一条数据)?

没必要。

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

php 包含 implodejoin,它们在这里会更好:

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

只需让您的 if 子句使用 end 函数:

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