I am working on a mailing list.
My mail list has over 400 emails right now, so I am using foreach
.
My question is: Can I limit foreach for only 100 emails?
Eg - Send an email to the first 100 emails, break, then start from where it stopped. So, for example, for 400 emails, foreach to be called 4 times to send an email to all the emails.
foreach ($addresses as $to) {
mail($to,$subject,$message,$headers);
}
I need to do it that way because if I send the email to all 400 emails at once, I get 503 service unavailable.
I tried this but doesn't work...
$emailchunkarray = array_chunk($addresses, 50);
$arraysize = count ($emailchunkarray);
$x = 0;
function chunker() {
if ($x <= $arraysize) {
foreach ($emailchunkarray[$x] as $to) {
mail($to,$subject,$message,$headers);
}
$x++
$chunker2();
}
}
$chunker();
function chunker2() {
if ($x <= $arraysize) {
foreach ($emailchunkarray[$x] as $to){
mail($to,$subject,$message,$headers);
}
$x++;
$chunker();
}
}
For some reason I can't answer my question... So here is how I did it:
$ChunkAddresses = 10;
$EmailChunkArray = array_chunk($Addresses, $ChunkAddresses);
$ArraySize = count ($EmailChunkArray);
$ChunkSize = 0;
$ForeachCounter = 0;
ChunkLoop: {
if ($GLOBALS["ChunkSize"] <= $GLOBALS["ArraySize"]) {
$EmailChunkArrayLoop = $GLOBALS["EmailChunkArray"];
foreach ($EmailChunkArrayLoop[$GLOBALS["ChunkSize"]] as $ToChunkLoop) {
mail($ToChunkLoop,$GLOBALS["Subject"],$GLOBALS["Message"],$GLOBALS["Headers"]);
$GLOBALS["ForeachCounter"]++;
if ($GLOBALS["ForeachCounter"] == $GLOBALS["ChunkAddresses"]) {
echo "This is the " . $GLOBALS["ChunkSize"] . " chunk.";
$GLOBALS["ForeachCounter"] = 0;
break 1;}
}
$GLOBALS["ChunkSize"]++;
sleep(3);
goto ChunkLoopFollow;} else if ($GLOBALS["ChunkSize"] == $GLOBALS["ArraySize"]){
exit();}
}
ChunkLoopFollow: {
if ($GLOBALS["ChunkSize"] <= $GLOBALS["ArraySize"]) {
$EmailChunkArrayLoopFollow = $GLOBALS["EmailChunkArray"];
foreach ($EmailChunkArrayLoopFollow[$GLOBALS["ChunkSize"]] as $ToChunkLoopFollow) {
mail($ToChunkLoopFollow,$GLOBALS["Subject"],$GLOBALS["Message"],$GLOBALS["Headers"]);
$GLOBALS["ForeachCounter"]++;
if ($GLOBALS["ForeachCounter"] == $GLOBALS["ChunkAddresses"]) {
echo "This is the " . $GLOBALS["ChunkSize"] . " chunk.";
$GLOBALS["ForeachCounter"] = 0;
break 1;}
}
$GLOBALS["ChunkSize"]++;
sleep(3);
goto ChunkLoop;} else if ($GLOBALS["ChunkSize"] == $GLOBALS["ArraySize"]){
exit();}
}
echo "Finished!";