The function foreach()
waits for an eternal object like a stdclass
or a array
.
To avoid the Invalid argument supplied for foreach()
, just create a consistent code by checking if the parameter is iterable and has the necessary data for routine execution.
Example for the type array
:
$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 the type stdclass
$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 code with a consistent stream as there is no way to ignore a fatal error type. This error level may even be hidden but cannot prevent the compiler from interrupting execution.
Note that when PHP runs in CGI mode, a fatal error is dispatched in the same output as display_errors
be as OFF.
If you still have doubt, take the test:
$arr = 1;
try{
foreach ($arr as $v) {
echo $v;
}
} catch (Exception $e) {
// Não funfa para fatal error.
}
The try/catch
does not capture type errors fatal error.
You need to give more details about this ...
– rray
Starting with the code. Because no one will answer
try{}catch(exception){//faz nada};
. Remember that generic questions only deserve generic answers.– DH.