Search code examples
phpvariablesconcatenation

Removing unnecessary commas when concatenating variables into a comma separated list?


When I concatenate PHP variables to form a comma separated list it adds a comma regardless of whether or not that variable has a value.

How can I remove the unnecessary commas when concatenating variables into a comma separated list?

try {
    $stmt = $conn->prepare("SELECT * FROM customer_info WHERE user_id = :user_id");
    $stmt->bindValue(':user_id', $user_id);
    $stmt->execute();
}
catch (PDOException $e) {
    echo $e->getMessage();
}
$search = array('_', ',', 'Null');
$replace = array(' ', ', ', '');
$rows = str_replace($search, $replace, $row);

$merged_likes = $rows['items_like'] . ",  " . $rows['first_like'] . ",  " . $rows['second_like'] . ",  " . $rows['third_like'];
echo $merged_likes;

Solution

  • See my answer to your other question. Once you have the items in an array, just filter out anything that's blank with array_filter(). Example:

    $likes = array_filter($likes, function($item)
    {
        return !empty($item);
    });
    
    echo implode(', ', $likes);
    

    This syntax will only work with PHP >=5.3.0. See anonymous functions for more information.

    Edit

    As KingCrunch mentions below, if all of your blank items evaluate to false (e.g., an empty string), you can simply omit the callback function:

    $likes = array_filter($likes);
    echo implode(', ', $likes);
    
    // or more succinctly
    
    echo implode(', ', array_filter($likes));