What is the common error message "Invalid argument supplied for foreach()" in PHP and how can it be resolved?
The "Invalid argument supplied for foreach()" error in PHP occurs when you try to loop through a variable using foreach() that is not an array or an object that implements the Traversable interface. To resolve this issue, you should check if the variable is an array or an object before using foreach().
// Check if the variable is an array or an object before using foreach()
if(is_array($variable) || $variable instanceof Traversable) {
foreach($variable as $item) {
// Loop through the variable
}
} else {
// Handle the case when the variable is not iterable
echo "Invalid argument supplied for foreach()";
}
Keywords
Related Questions
- How can PHPMailer be utilized to avoid errors when sending emails with attachments in PHP?
- How can I streamline the process of creating and executing SQL files from PHP scripts for database integration?
- What are some common methods for rounding numerical values in PHP to a specific number of decimal places?