Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid output foreach error?

Tags:

foreach

php

In this article, it mentions:

foreach does not support the ability to suppress error messages using '@'.

How do I avoid an output foreach error? I do not want see:

Warning: Invalid argument supplied for foreach()

Is there a way to make an if else judgement?

like image 821
yuli chika Avatar asked Jun 04 '11 23:06

yuli chika


2 Answers

Before foreach check if variable contain array:

if (is_array($var))
{
   foreach...
}
like image 161
OZ_ Avatar answered Sep 30 '22 13:09

OZ_


prefix the variable with a (array) like this.

foreach( (array) $array_thats_not_an_array as $key => $value ){
    echo $key . ' ' . $value;
}
like image 26
Mient-jan Stelling Avatar answered Sep 30 '22 15:09

Mient-jan Stelling