1

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.. i.e. I'd like to find a simple repeatable approach that can be used whenever 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 i.e., 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.

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

2 Comments

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")?
use use explode to turn a string to an array of elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.