How can I blow up an array by skipping empty array elements?

Perl join() ignores (skips) empty array values; PHP implode() not displayed.

Suppose I have an array:

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

gives:

 one---four--six 

instead of (IMHO preferable):

 one-four-six 

Any other inline functions with the behavior I'm looking for? Or will it be user work?

+65
php implode
May 12 '11 at 22:49
source share
7 answers

You can use array_filter() :

If no callback is specified, all input entries equal to FALSE (see conversion to a boolean value ) will be deleted.

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

Obviously, this will not work if your array has 0 (or any other value that evaluates to FALSE ) and you want to save it. But then you can provide your own callback function.

+143
May 12 '11 at 22:52
source share

I suppose you cannot consider it inline (because the function works with a user-defined function), but you can always use array_filter .
Something like:

 function rempty ($var) { return !($var == "" || $var == null); } $string = implode('-',array_filter($array, 'rempty')); 
+7
May 12 '11 at 22:53
source share

How you should implement the filter depends only 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")); } 
+3
May 12 '11 at 23:10
source share

Based on what I can find, I would say there is a chance that there really is no way to use the built-in PHP for this. But you could probably do something like that:

 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; } 
+1
May 12 '11 at 22:56
source share

Try the following:

 $result = array(); foreach($array as $row) { if ($row != '') { array_push($result, $row); } } implode('-', $result); 
+1
May 12 '11 at 22:56
source share

array_fileter() seems to be acceptable here and probably remains tbh's most reliable answer.

However, the following will also be done if you can guarantee that the glue symbol does not already exist in the lines of each element of the array (which would be set in most practical cases), otherwise you would not be able to distinguish glue from the actual data in the array):

 $array = array('one', '', '', 'four', '', 'six'); $str = implode('-', $array); $str = preg_replace ('/(-)+/', '\1', $str); 
0
Nov 04 '17 at 13:05
source share

Try the following:

 if(isset($array)) $array = implode(",", (array)$array); 
-2
Dec 02 '13 at 8:00
source share



All Articles