How can I implode an array while skipping empty ar

2019-02-01 15:45发布

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

Suppose I have an array:

$array = array('one', '', '', 'four', '', 'six');
implode('-', $array);

yields:

one---four--six

instead of (IMHO the preferable):

one-four-six

Any other built-ins with the behaviour I'm looking for? Or is it going to be a custom jobbie?

标签: php implode
8条回答
叛逆
2楼-- · 2019-02-01 15:51

Try this:

if(isset($array))  $array = implode(",", (array)$array);
查看更多
闹够了就滚
3楼-- · 2019-02-01 16:03

To remove null, false, empty string but preserve 0, etc. use func. 'strlen'

$arr = [null, false, "", 0, "0", "1", "2", "false"];
print_r(array_filter($arr, 'strlen'));

will output:

//Array ( [3] => 0 [4] => 0 [5] => 1 [6] => 2 [7] => false )
查看更多
smile是对你的礼貌
4楼-- · 2019-02-01 16:08

I suppose you can't consider it built in (because the function is running with a user defined function), but you could always use array_filter.
Something like:

function rempty ($var)
{
    return !($var == "" || $var == null);
}
$string = implode('-',array_filter($array, 'rempty'));
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-02-01 16:09

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"));
} 
查看更多
SAY GOODBYE
6楼-- · 2019-02-01 16:12

Try this:

$result = array();

foreach($array as $row) { 
   if ($row != '') {
   array_push($result, $row); 
   }
}

implode('-', $result);
查看更多
Summer. ? 凉城
7楼-- · 2019-02-01 16:13

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.

查看更多
登录 后发表回答