Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

implode

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?

like image 760
Tom Auger Avatar asked May 12 '11 22:05

Tom Auger


People also ask

How do you implode an array of arrays?

PHP Implode Function The implode function in PHP is used to "join elements of an array with a string". The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice.

How do you clear an empty array?

Answer: Use the PHP array_filter() function You can simply use the PHP array_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function.


2 Answers

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.

like image 84
Felix Kling Avatar answered Nov 16 '22 00:11

Felix Kling


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')); 
like image 34
Ben Avatar answered Nov 16 '22 00:11

Ben