Skip to content
PHP Logo

What are some best practices for ensuring that the array is not empty when using preg_match_all and file_get_contents in PHP?

When using preg_match_all with file_get_contents in PHP, it is important to check if the array returned by preg_match_all is not empty before further processing. This can be done by checking if the array is not false and if it has any elements. This helps prevent errors when trying to access elements of an empty array.

php
$content = file_get_contents('example.txt');
if ($content !== false) {
    preg_match_all('/pattern/', $content, $matches);
    
    if (!empty($matches[0])) {
        // Array is not empty, do further processing
    } else {
        // Array is empty, handle accordingly
    }
} else {
    // Error handling for file_get_contents failure
}