How to avoid foreach output error?

In this article, she mentions:

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

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

Warning Invalid argument provided by foreach ()

Is there any way to make an if else decision?

+6
source share
4 answers

Before foreach checks to see if a variable contains an array:

 if (is_array($var)) { foreach... } 
+5
source

variable prefix with (array) as follows.

 foreach( (array) $array_thats_not_an_array as $key => $value ){ echo $key . ' ' . $value; } 
+5
source
 if(!empty($array)) { foreach($array as $a) { // do something } } 
0
source

I used the OZ clause but got an error in the is_array test.

But adding @ in front of the name of the array to be tested worked.

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

and yes, I know that using @ is shoddy, but I can't get a tiny bit of legacy code that works beautifully. I can spend another hour to fix this, to get around "your var is not defined" or insert @ in and get other things necessary for the ALFA version to share with a friend tomorrow. Oh yes, 11 p.m., and my brain is confused!

ATB Mr. Grumpy
PS Thank you very much OZ_ for the 95% solution!

0
source

Source: https://habr.com/ru/post/889793/


All Articles