note 105933 added to control-structures.foreach

From: Date: Mon, 26 Sep 2011 19:36:13 +0000
Subject: note 105933 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-183457@lists.php.net to get a copy of this message
"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... ---- Server IP: 92.48.74.199 Probable Submitter: 178.36.182.246 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/105933 Del: integrated -- https://master.php.net/note/delete/105933/integrated Del: useless -- https://master.php.net/note/delete/105933/useless Del: bad code -- https://master.php.net/note/delete/105933/bad+code Del: spam -- https://master.php.net/note/delete/105933/spam Del: non-english -- https://master.php.net/note/delete/105933/non-english Del: in docs -- https://master.php.net/note/delete/105933/in+docs Del: other reasons-- https://master.php.net/note/delete/105933 Reject -- https://master.php.net/note/reject/105933 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#183457) next »