开发者

Handling empty arrays with foreach

开发者 https://www.devze.com 2023-03-21 10:15 出处:网络
$foo = \'\'; foreach((array)$foo as $f){ echo \'xxx\'; } Wil开发者_如何转开发l still output \'xxx\'...(array)$foo:
$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

精彩评论

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