Mohamed Saleh Mohamed Saleh - 3 months ago 37
PHP Question

php foreach every 100 times sleep then continue

i have a foreach loop and 5000 user in my site
and i want to send them emails

every 10 member sleep 5 second then continue

$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: Sender Name <sender@domain.com>";
$headers[] = "Bcc: JJ Chong <bcc@domain2.com>";
$headers[] = "Reply-To: Recipient Name <receiver@domain3.com>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

$users = array('mohamed','ahmed');
foreach($users as $user){
mail($user, $subject, $email, implode("\r\n", $headers));
}


how to do it

Answer

Use the modulus operator to detect multiples of 10.

foreach ($users as $i => $user) {
    mail($user, $subject, $email, implode("\r\n", $headers));
    if ($i > 0 && $i % 10 == 0) {
        sleep(5);
    }
}
Comments