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

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

    Try this:

    if(isset($array))  $array = implode(",", (array)$array);
    
    0 讨论(0)
  • 2020-12-23 13:47

    Try this:

    $result = array();
    
    foreach($array as $row) { 
       if ($row != '') {
       array_push($result, $row); 
       }
    }
    
    implode('-', $result);
    
    0 讨论(0)
  • 2020-12-23 13:50

    Based on what I can find, I'd say chances are, there isn't really any way to use a PHP built in for that. But you could probably do something along the lines of this:

    function implode_skip_empty($glue,$arr) {
          $ret = "";
          $len = sizeof($arr);
          for($i=0;$i<$len;$i++) {
              $val = $arr[$i];    
              if($val == "") {
                  continue;
              } else {
                $ret .= $arr.($i+1==$len)?"":$glue;
              }
          }
          return $ret;
    }
    
    0 讨论(0)
提交回复
热议问题