开发者

how to avoid output foreach error?

开发者 https://www.devze.com 2023-03-10 16:56 出处:网络
In this article, it mentions: foreach does not support the ability to suppress error messages using \'@\'.

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 t开发者_开发知识库o make an if else judgement?


Before foreach check if variable contain array:

if (is_array($var))
{
   foreach...
}


prefix the variable with a (array) like this.

foreach( (array) $array_thats_not_an_array as $key => $value ){
    echo $key . ' ' . $value;
}


if(!empty($array)) {
  foreach($array as $a) {
    // do something
  }
}


I used OZ's suggestion but got an error on the is_array test.

But adding a @ before the name of the array to be tested worked a treat.

    if (is_array((@$errors))){
      foreach ($errors as $error): ?>
        <?php echo $error; ?>
        <br/>
      <?php endforeach;
    }

and yes I know using @ is shoddy BUT I cannot get a tiny bit of inherited code working prettily. I can either spend another hour to fix that to get round a "your var is not defined" or stick a @ in and get the other things needed for a very ALFA version to share with a friend tomorrow. Oh and yes 11 pm and my brain is befuddled!

ATB Mr Grumpy
PS Big thanks to OZ_ for 95% of the solution!

0

精彩评论

暂无评论...
验证码 换一张
取 消