What are some common pitfalls when using preg_match and foreach in PHP?

One common pitfall when using preg_match and foreach in PHP is not checking if preg_match returns a valid result before using foreach on the matches. This can lead to errors if preg_match does not find any matches. To solve this, you should always check if preg_match returns a valid result before iterating over the matches with foreach.

// Check if preg_match returns a valid result before using foreach
if (preg_match('/pattern/', $string, $matches)) {
    foreach ($matches as $match) {
        // Process each match
    }
} else {
    // Handle case when no matches are found
}