php – how to avoid output foreach error?-ThrowExceptions

Exception or error:

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?

How to solve:

Before foreach check if variable contain array:

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

Answer:

prefix the variable with a (array) like this.

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

Answer:

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

Answer:

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!

Leave a Reply

Your email address will not be published. Required fields are marked *