I am looping over a twitter feed and everything in my code works fine, but I am struggling with one thing. The if statement towards the bottom returns all messages that have a date for today. Then based on that I have a regex pattern I am trying to test for. If its found I state “found it” and if not I state “not found”. What I need help with is the not found part. Rather than stating “not found” for each message how can I make it so that it will loop over the messages and if found state “found it” and stop everything, but if not found pass over the message and then once all the looping is done state “not found” only once.
$dom = new DOMDocument();
@$dom->loadHTMLFile('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=google');
$xml = simplexml_import_dom($dom);
$twitter = $xml->xpath("//item");
foreach ($twitter as $item) {
$timezone = new DateTimeZone('America/Los_Angeles');
$date = new DateTime($item->pubdate);
$date->setTimeZone($timezone);
$twitter_date = $date->format("F j Y");
$todays_date = date("F j Y");
if ($twitter_date == $todays_date) {
$text = $item->title;
$pattern = '/\s\d\s\d/i';
if (preg_match($pattern, $text, $codes)) {
if (isset($codes[0])) {
echo 'found it!';
}
} else {
echo 'not found';
}
}
}
You can keep a flag variable
$foundto track whether it was found, and thenbreakout of the loop when one is found. Then after yourforeachloop, check the value of$found.