submitted by:

PHP: Foreach with empty array

This is a gem. PHP's foreach iterator will throw an error if an empty or non-array is passed. To return a null result instead, typecast the input variable using array().

code snippet:

foreach ((array) $non_array as $key => $val) {
"Key $key, Value $val\n";

This gem is from brian at diamondsea dot com via the php documentation site: A common problem is having PHP generate an error when trying to iterate through an array that may sometimes have no data in it. This causes PHP to generate a warning such as: Warning: Invalid argument supplied for foreach() in test.php on line 14 You can prevent this error by type-casting the foreach variable as an array type using "(array)" before the array variable name.