implode()上的参数错误捕获无效

时间:2011-04-16 12:50:32

标签: php error-handling

在下面的脚本中,我在“echo implode()”行中收到无效的参数错误:

  

警告:implode()[function.implode]:   传入的参数无效......

这是脚本:

if ( !function_exists('wp_tag_cloud') || get_option('cb2_noposttags')) return;
$unlinkTags = get_option('cb2_unlinkTags'); 
echo '<div class="links"><h2>Tags</h2>';
if($unlinkTags)
{
        $tags = get_tags();
        foreach ($tags as $tag){
            $ret[]= $tag->name;
        }
        echo implode(', ', $ret);
}
else
{
    wp_tag_cloud('separator=, &smallest=11&largest=11');
}
echo '</div>';

我如何重写这个来捕捉无效的论点?

3 个答案:

答案 0 :(得分:3)

只需在循环之前添加:$ret = array();

目前,如果你的for循环中没有添加任何内容,则不会定义$ ret。

答案 1 :(得分:3)

在你的foreach循环

之前,将$ ret初始化为数组
$ret = array();
$tags = get_tags();
foreach ($tags as $tag){
   $ret[]= $tag->name; 
} 
echo implode(', ', $ret); 

然后,如果get_tags()没有返回任何内容,$ ret仍然作为数组传递给implode(但作为一个空数组)而不是null

答案 2 :(得分:1)

对于稍微不同的味道,你可以测试它是否是一个数组:

if (is_array($ret)) echo implode(', ', $ret);