How can the foreach loop in PHP be effectively used to iterate through arrays without causing errors like "Invalid argument supplied for foreach()"?

When using a foreach loop in PHP to iterate through an array, it is important to ensure that the array being looped through is actually an array. If an invalid argument, such as a non-array variable or null, is passed to the foreach loop, it will result in the error "Invalid argument supplied for foreach()". To prevent this error, you can first check if the variable is an array before using the foreach loop.

// Check if the variable is an array before using foreach
if(is_array($array)) {
    foreach($array as $item) {
        // Loop through the array elements
        echo $item;
    }
} else {
    // Handle the case where $array is not an array
    echo "Invalid argument supplied for foreach";
}