I have a bunch of variables I want to display of which some are empty. Some vars have spaces in them I want to preserve. I would like to display them as a comma delimited list. If I echo them sequentially var1, var2,.var6,.var10, I get extra commas where there are empties. Doesn't sound like it would be that hard to delete the extra commas, but my ideas have not worked.

Since I have many, many of these, I don't want to have to condition printing every one--allowing for first or last in placement of commas or iteratively replacing multiple commas with 1 comma or something complicated.. ie I'd like to find a simple repeatabl approach that can be used whenver this comes up.

One idea was to convert the string into an array and delete empty values. I can strip out empty spaces and echoing,can print var1,var2,,,var8,,, with no problem. However, I can't find a way to delete the commas ie, the empty values in array.

I tried:

$array = "one,two,,,six,,,ten";
$array= array_filter($array);
foreach($array as $val) {
echo $val;}}
foreach($array as $val) {
if ($val!=""&$val!=NULL) {
echo $val;}}
}

it doesn't get rid of commas. Have not had luck with following suggestions on web:

array_flip(array_flip($array); or
$array = array_values($array); or

Could be typo on my end, but would appreciate any suggestions from the experienced.

Thanks

link|improve this question

66% accept rate
feedback

1 Answer

up vote 5 down vote accepted

The reason you can not delete then is because you are not working with a valid array .. to work with a valid array you need to do this :

$array = "one,two,,,six,,,ten";
$array = explode(",",$array);
$array= array_filter($array);

var_dump($array);

Output

array
  0 => string 'one' (length=3)
  1 => string 'two' (length=3)
  4 => string 'six' (length=3)
  7 => string 'ten' (length=3)

To convert back to string use implode http://php.net/manual/en/function.implode.php

    var_dump(implode(",", $array))

Output

string 'one,two,six,ten' (length=15)

Thanks :)

link|improve this answer
I left out a line $array = array("one,two,three"); which I was using instead of explode however, that must not have been doing the trick as using explode did allow the filter to work. I was able to trim the array to the desired values. Echoing, did not produce commas. So I took your second suggestion and imploded and this did the job. Thanks! Out of curiosity as I am learning, what is the difference between explode and array("one","two", 'three")? – user1260310 Apr 2 at 21:24
use use explode to turn a string to an array of elements – Baba Apr 2 at 22:24
+1 for the extensive answer! – Hans Wassink Apr 5 at 13:48
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.