Jump to content

return true if foreach loop passes


AdRock

Recommended Posts

IHere is my problem....

 

I have a foreach loop which has an array of emails which i send an email to.

 

I need to be able to, if all emails send return a true value and if any of them fail, return false.

 

I can't put the return in the foreach loop becuase if the first one passes it has returned true already

 

Here is my loop

foreach($emails as $email) {
$to = $email;

$HTML = str_replace($nameholder, $names, $HTML);
$HTML = str_replace($emailholder, $email, $HTML);

$result = sendHTMLemail($HTML,$from,$to,$subject);

if($result == 'Correct') {
	return 'Correct';
}
else {
	return "Emails not sent";
}
}

 

I need to take the IF statement out but can i appy the $result to the foreach loop?

Link to comment
https://forums.phpfreaks.com/topic/149902-return-true-if-foreach-loop-passes/
Share on other sites


foreach($emails as $email) {
$to = $email;

$HTML = str_replace($nameholder, $names, $HTML);
$HTML = str_replace($emailholder, $email, $HTML);

$result = sendHTMLemail($HTML,$from,$to,$subject);

if($result != 'Correct') {
	return "Emails not sent";
}
}
return 'Correct';

Or you could use a temp variable which would store true or false result. However, the method by samshel is much more efficient.

$temp=1;
foreach($emails as $email) {
$to = $email;

$HTML = str_replace($nameholder, $names, $HTML);
$HTML = str_replace($emailholder, $email, $HTML);

$result = sendHTMLemail($HTML,$from,$to,$subject);

if($result != 'Correct') {
	$temp=0;
}
}
if($temp==1) {
return "All Emails Sent"
}
else {
return "All Emails Not Sent"
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.