The foreach()
function expects an iterable object as a stdclass
or a array
.
To avoid% w / o, just create a consistent code by verifying that the parameter is iterable and has the data required to run the routine.
Example for type Invalid argument supplied for foreach()
:
$n = 0;
if ($n == 1) {
$arr = array(1, 2, 3);
}
// Aqui usamos is_array() pois esperamos um array.
if (isset($arr) && is_array($arr) && !empty($arr)) {
foreach ($arr as $v) {
echo $v;
}
}
Example for type array
$n = 0;
if ($n == 1) {
$arr = (object)array(1, 2, 3);
}
// Aqui usamos is_object() pois esperamos um stdClass
if (isset($arr) && is_object($arr) && !empty($arr)) {
foreach ($arr as $v) {
echo $v;
}
}
As for the second error, it is probably a consequence of the first error. A chain reaction.
In short, just create codes with a consistent flow because there is no way to ignore a fatal error type error. This level of error may even be hidden, but it can not prevent the compiler from stopping execution.
Note that when PHP runs in CGI mode, a fatal error is dispatched in the output even though stdclass
is OFF .
If you still have questions, take the test:
$arr = 1;
try{
foreach ($arr as $v) {
echo $v;
}
} catch (Exception $e) {
// Não funfa para fatal error.
}
display_errors
does not catch fatal error errors.