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

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

    You can use array_filter():

    If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

    implode('-', array_filter($array));
    

    Obviously this will not work if you have 0 (or any other value that evaluates to false) in your array and you want to keep it. But then you can provide your own callback function.

提交回复
热议问题