AdRock Posted March 17, 2009 Share Posted March 17, 2009 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? Quote Link to comment https://forums.phpfreaks.com/topic/149902-return-true-if-foreach-loop-passes/ Share on other sites More sharing options...
samshel Posted March 17, 2009 Share Posted March 17, 2009 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'; Quote Link to comment https://forums.phpfreaks.com/topic/149902-return-true-if-foreach-loop-passes/#findComment-787252 Share on other sites More sharing options...
dpacmittal Posted March 18, 2009 Share Posted March 18, 2009 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" } Quote Link to comment https://forums.phpfreaks.com/topic/149902-return-true-if-foreach-loop-passes/#findComment-787430 Share on other sites More sharing options...
Daniel0 Posted March 18, 2009 Share Posted March 18, 2009 However, the method by samshel is much more efficient. No, yours is better. samshel's will not complete the remainder of items in the loop if the first email is sent. Quote Link to comment https://forums.phpfreaks.com/topic/149902-return-true-if-foreach-loop-passes/#findComment-787438 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.