Question: I am stuck with a problem, I have fetched some values from a MySQL query and put them in to an array like so:

```
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;

$fullAddress = [$add1, $add2, $twn, $pcode];

$string = rtrim(implode(',', $fullAddress), ',');

echo $string;

```

so that I can echo out a users address. The problem I am getting is that even if one of these values does not exist (and some don't because they are not all required fields), the comma is still echoed to the screen like:

```
add1,, town, br2 5lp 

```

because there is an empty value in the database.

What I want to achieve is something like:

```
add1, town, br2 5lp 

```

if the second part of the address is missing.

Can anyone help me figure this out?

Answer: 
try this.

```
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = implode(',', array_filter($fullAddress, 'strlen'));
echo $string;

```
```
The problem I am getting is that even if one of these values does not
exist (and some dont because they are not all required fields), 
the comma is still echoed to the screen 

```

That is what the implode function in php is supposed to do. If you want a different behavior, you will have to either change the way you create your CSV string or do some extra processing on the information you obtain from the implode function.

So use a for loop or a foreach loop to go through the address array. A for loop is faster than a foreach loop.

Using Foreach:

```
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;

$fullAddress = [$add1, $add2, $twn, $pcode];

$string = "";
foreach($fullAddress as $value)
{
     if(!empty($value))
          $string .= $value.", ";
}

$string = rtrim($string, ", ");

echo $string;

```

You can do some extra processing on the created csv string of your own solution by maybe doing a `str_replace()` of all occurances of `,,` with `,`. This could be dangerous because if any of the values in your $fullAddress array contain a `,,` as a valid string then that will also be replaced too with `,`.