开发者

Handling empty arrays with foreach

$foo = '';

foreach((array)$foo as $f){
  echo 'xxx';
}

Wil开发者_如何转开发l still output 'xxx'...


(array)$foo:

This is not empty array, but array which contains an empty element.


Yes, it will output 'XXX', because the string variable $foo = '' converted to array will become:

array(
    0 => ''
)


First of all, you are not creating an empty array by type casting the following statement. The below code would actually produce an array with an empty string in its first element.

$foo = '';
(array)$foo;

So, the correct way, to create an empty array is

$foo = array();
foreach($foo as $f){
   echo 'xxx';
}

Hope, this helps you ...


if(!empty($foo))
    foreach((array)$foo as $f)
    {
      echo 'xxx';
    }


I always check for type and contents before I perform a foreach. E.g.

if( is_array($foo) && sizeof($foo) <> 0)
{
 // do foreach
}


Casting an empty string to an array won't result in an empty array. It will create an array with an empty string as an item:

array(
    0 => ''
)

You could check if it's a valid array:

if(is_array($foo))
{
    foreach($foo as $f)
    {
        echo 'xxx';
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜