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

前端 未结 9 524
没有蜡笔的小新
没有蜡笔的小新 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:43

    array_fileter() seems to be the accepted way here, and is probably still the most robust answer tbh.

    However, the following will also work if you can guarantee that the "glue" character doesn't already exist in the strings of each array element (which would be a given under most practical circumstances -- otherwise you wouldn't be able to distinguish the glue from the actual data in the array):

    $array = array('one', '', '', 'four', '', 'six');
    $str   = implode('-', $array);
    $str   = preg_replace ('/(-)+/', '\1', $str);
    

提交回复
热议问题