In the context of PHP development, what are some best practices for handling empty or non-existent arrays returned by preg_match()?

When using preg_match() in PHP, it's important to handle cases where the function returns an empty or non-existent array. One common best practice is to check if the array is empty before trying to access its elements to avoid errors. This can be done using functions like empty() or count() to determine if there are any matches before proceeding with further processing.

// Example of handling empty or non-existent arrays returned by preg_match()

$string = "Hello, World!";
$pattern = "/foo/";

if (preg_match($pattern, $string, $matches)) {
    // Check if the array is not empty before accessing its elements
    if (!empty($matches)) {
        // Process the matches found
        foreach ($matches as $match) {
            echo $match . "\n";
        }
    } else {
        echo "No matches found.\n";
    }
} else {
    echo "Error in regex pattern.\n";
}