What are some best practices for sending emails within a foreach loop in PHP?

When sending emails within a foreach loop in PHP, it is important to optimize the code to prevent performance issues and ensure that emails are sent efficiently. One way to achieve this is by using a separate function to send emails, rather than sending them directly within the loop. This helps to streamline the process and avoid unnecessary overhead.

// Define a function to send emails
function sendEmail($recipient, $subject, $message) {
    // Code to send email using PHP's mail() function or a library like PHPMailer
}

// Example foreach loop to send emails
$recipients = ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com'];

foreach ($recipients as $recipient) {
    $subject = 'Your Subject Here';
    $message = 'Your Message Here';
    
    sendEmail($recipient, $subject, $message);
}