Skip to content
PHP Logo

What are the best practices for handling empty arrays in PHP when using foreach loops?

When handling empty arrays in PHP with foreach loops, it's important to check if the array is empty before iterating over it to avoid errors or unexpected behavior. One way to handle this is by using the `empty()` function to check if the array is empty before entering the foreach loop.

php
// Check if the array is empty before using foreach loop
if (!empty($array)) {
    foreach ($array as $item) {
        // Loop through the array items
        echo $item . "<br>";
    }
} else {
    // Handle the case when the array is empty
    echo "Array is empty";
}