note 105933 deleted from control-structures.foreach by googleguy
| From: | googleguy@php.net | Date: | Wed, 14 Nov 2012 22:20:35 +0000 |
| Subject: | note 105933 deleted from control-structures.foreach by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191943@lists.php.net to get a copy of this message | ||
Note Submitter: glitch dot mr at gmail dot com
----
"foreach does not support the ability to suppress error messages using '@'."
That's not exactly true. It's indeed not possible to do turn off error reporting for
foreach(){} instruction itself.
<?php
@foreach($array as $value){} // invalid, unexpected T_FOREACH
?>
But, it's possible to turn off every possible way of having error by casting $variable to array
and using @ operator on it to ignore possible errors. Note that this code WILL run one loop on your
code if it isn't array with actual value. If it's OK, you might use it, but if it's
not acceptable look for solutions below.
<?php
foreach((array) @$array as $value){}
?>
If you don't like this behavior you can use in_array() function to check if it's array and
use empty array if it isn't array and use correct way depending on type of value.
<?php
foreach(is_array($array) || is_object($array) ? $array : array() as $value){}
?>
If you don't like all this variable abuse (for example if you have more complex code, you can
make assigment in your foreach() code (note that this way it's way more complex and pretty
obfuscated)).
<?php
// will parse every array inside this array in reverse order
foreach(is_array($_ = array_shift($array)) || is_object($_) ? $_ : array() as $value){}
?>
Of course usually it's just enough to check if value is array, or just accept it anyways if
there is no chance that it could be anything else. Or you could turn off error_reporting() before
accessing foreach(){} and turning it on shortly after that...
But actually, this is not existing problem. In fact, all those warnings help to find errors in your
code and I personally wouldn't want to avoid such things. if(@$a){} is personally for fine
replacement of empty() through...