How can I implode an array while skipping empty array items?

前端 未结 9 535
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 12:45

Perl\'s join() ignores (skips) empty array values; PHP\'s implode() does not appear to.

Suppose I have an array:

$array = a         


        
9条回答
  •  心在旅途
    2020-12-23 13:44

    How you should implement you filter only depends on what you see as "empty".

    function my_filter($item)
    {
        return !empty($item); // Will discard 0, 0.0, '0', '', NULL, array() of FALSE
        // Or...
        return !is_null($item); // Will only discard NULL
        // or...
        return $item != "" && $item !== NULL; // Discards empty strings and NULL
        // or... whatever test you feel like doing
    }
    
    function my_join($array)
    {
        return implode('-',array_filter($array,"my_filter"));
    } 
    

提交回复
热议问题