What are best practices for handling empty arrays in PHP to prevent errors like InvalidArgumentException?

When working with arrays in PHP, it is important to check if an array is empty before performing operations on it to prevent errors like InvalidArgumentException. One way to handle empty arrays is to use the empty() function to check if the array is empty before attempting to access its elements.

// Check if the array is empty before performing operations
if(!empty($array)) {
    // Perform operations on the array
    foreach($array as $element) {
        // Process each element
    }
} else {
    // Handle the case when the array is empty
    echo "Array is empty";
}