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

PhpImplode

Php Problem Overview


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 Solutions


Solution 1 - Php

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.

Solution 2 - Php

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'));

Solution 3 - Php

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 )

Solution 4 - Php

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"));
} 

Solution 5 - Php

$array = ["one", NULL, "two", NULL, "three"];
$string = implode("-", array_diff($array, [NULL]));
echo $string;

Returns one-two-three

Solution 6 - Php

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;
}

Solution 7 - Php

Try this:

$result = array();

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

implode('-', $result);

Solution 8 - Php

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);

Solution 9 - Php

Try this:

if(isset($array))  $array = implode(",", (array)$array);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom AugerView Question on Stackoverflow
Solution 1 - PhpFelix KlingView Answer on Stackoverflow
Solution 2 - PhpJessView Answer on Stackoverflow
Solution 3 - PhpAli VarliView Answer on Stackoverflow
Solution 4 - PhpThomas HupkensView Answer on Stackoverflow
Solution 5 - PhpRyan PrescottView Answer on Stackoverflow
Solution 6 - PhpozzmotikView Answer on Stackoverflow
Solution 7 - PhpJeremyView Answer on Stackoverflow
Solution 8 - PhpcartbeforehorseView Answer on Stackoverflow
Solution 9 - Phpuser2775080View Answer on Stackoverflow