preg_match () and preg_match_all () return the number of matches found or false in case of an error. However, this means that it will return 0 if no matches are found, so checking explicitly for false, and then trying to loop through an empty set will still be problematic.
Usually I check false and then check the number of matches again before the loop results. Sort of:
$match = preg_match_all($pattern, $subject, $matches); if($match !== false) { if(count($matches) > 0) { foreach($matches as $k=>$v) { ... } } else { user_error('Sorry, no matches found'); } } else { die('Match error'); }
source share