5 Ways to Remove Trailing JSON Comma In While Loop PHP

Oh yes, the dreaded trailing comma that completely ruins validation of JSON. It’s a typical nightmare when using the database to create some JSON within a while loop. When using PHP, there is quite a few ways to handle this problem and I am going to go through each one of them.

1. Using an If Statement to handle trailing commas

This, is by far my favorite way to remove the trailing comma from JSON when generating it within a while loop. A simple if statement to handle all of our trailing comma problems. This method also, in my opinion offers greater flexibility to accomplish highly customized JSON.

As you can see from this code and output, the comma is never left trailing, due to using the if statement and the preceding placement of the comma. Using this kinda long hand way of generating JSON within a while loop means by the time you are out of the while loop your JSON is properly formatted. No need for any additional functions to remove the trailing comma.

Here is the PHP

        $json = '[';
        $i = 0;
        while ($row = $result->fetch_assoc()) {
            if ($i == 0) { // On first loop use this block
                $json .= '{"label" : "' . $row["label"] . '", "value" : ' . $row["value"] . ' }';
            } else {
                // On the rest of the loops, use this block 
               // Notice the comma at the start. 
                $json .= ', {"label" : "' . $row["label"] . '", "value" : ' . $row["value"] . ' }';
            }
            $i++;
        }
        $json .= ']';
        echo $json;

JSON Output

[{
	"label": "blue",
	"value": 18
}, {
	"label": "red",
	"value": 20
}, {
	"label": "pink",
	"value": 4
}, {
	"label": "yellow",
	"value": 18
}, {
	"label": "green",
	"value": 21
}, {
	"label": "white",
	"value": 25
}, {
	"label": "black",
	"value": 15
}, {
	"label": "violet",
	"value": 12
}, {
	"label": "brown",
	"value": 13
}, {
	"label": "silver",
	"value": 18
}]

2. Using SubStr to remove trailing comma from json

Here is another way, which is less code, more efficient with regards to performance but feels less flexible overall. What we do is use SubStr the second we leave the while loop. We reformat the current $json variable by removing the last character in the $json variable, which, will be the trailing comma. After that, we can then add the last bracket to complete our JSON.

It is very important to note that the substring function must be executed before adding the final bracket, otherwise, that bracket will be removed rather than the comma.

PHP

$json = '[';
        while ($row = $result->fetch_assoc()) {
            $json .= '{"label" : "' . $row["label"] . '", "value" : ' . $row["value"] . ' } ,';
        }
        // Remove the trailing comma before we add the last bracket. 
        $json = substr($json, 0, -1); // Substring -1 character from the end of the json variable, this will be the trailing comma. 
        $json .= ']';

Json Output

[{
	"label": "blue",
	"value": 18
}, {
	"label": "red",
	"value": 20
}, {
	"label": "pink",
	"value": 4
}, {
	"label": "yellow",
	"value": 18
}, {
	"label": "green",
	"value": 21
}, {
	"label": "white",
	"value": 25
}, {
	"label": "black",
	"value": 15
}, {
	"label": "violet",
	"value": 12
}, {
	"label": "brown",
	"value": 13
}, {
	"label": "silver",
	"value": 18
}]

3. Using StrPos to get the position of the trailing comma and remove it

The trusty StrPos function finds any given character within a string, it will find the index of that character and also allow you to modify it on demand. With this scenario, we want to remove the comma altogether. The PHP code is not dissimilar to the substr method and to be honest, it will be a choice of preference to use it over substr or not.

PHP Code

$json = '[';
        while ($row = $result->fetch_assoc()) {
            $json .= '{"label" : "' . $row["label"] . '", "value" : ' . $row["value"] . ' } ,';
        }
        $json .= ']';
        $json[strrpos($json, ',')] = ''; // Find the last comma, and set it to blank, consequently, removing it.

JSON Output

[{
	"label": "blue",
	"value": 18
}, {
	"label": "red",
	"value": 20
}, {
	"label": "pink",
	"value": 4
}, {
	"label": "yellow",
	"value": 18
}, {
	"label": "green",
	"value": 21
}, {
	"label": "white",
	"value": 25
}, {
	"label": "black",
	"value": 15
}, {
	"label": "violet",
	"value": 12
}, {
	"label": "brown",
	"value": 13
}, {
	"label": "silver",
	"value": 18
}]

4. Removing Trailing Comma From While Loop Generated JSON with RTrim

RTrim is another quick and easy function to use, it simply trims a set character from the end (right) of any given string. It takes 2 parameters, firstly, the character we need to remove and secondly the large string we want to search and remove from. It’s somewhat similar to substr but still, it’s another viable way of removing commas from the end of a string. Again whats important here is that we use the rtrim method as soon as the while loop is broke out of. Otherwise we will end up removing the important closing bracket.

PHP

$json = '[';
        while ($row = $result->fetch_assoc()) {
            $json .= '{"label" : "' . $row["label"] . '", "value" : ' . $row["value"] . ' } ,';
        }
        // Remove the trailing comma before we add the last bracket. 
        $json = rtrim($json, ","); // // Find the last comma, and set it to blank, consequently, removing it.
        $json .= ']';

JSON Output

[{
	"label": "blue",
	"value": 18
}, {
	"label": "red",
	"value": 20
}, {
	"label": "pink",
	"value": 4
}, {
	"label": "yellow",
	"value": 18
}, {
	"label": "green",
	"value": 21
}, {
	"label": "white",
	"value": 25
}, {
	"label": "black",
	"value": 15
}, {
	"label": "violet",
	"value": 12
}, {
	"label": "brown",
	"value": 13
}, {
	"label": "silver",
	"value": 18
}]

5. Using Str_replace to search and remove comma

Using Str_replace as a solution to remove commas from the JSON you have produced within a while loop is another quick and dirty method. The only downside to this method is that it wouldn’t be great to expect re-usability from throughout projects. The reason being is that the str_replace depends on finding an exact search term and replacing it. Now let’s say your json changes and you have more nesting involved, it could be fatal!

$json = '[';
        while ($row = $result->fetch_assoc()) {
            $json .= '{"label" : "' . $row["label"] . '", "value" : ' . $row["value"] . ' } ,';
        }
        $json .= ']';
        $json = str_replace('},]', '}]', $json); // Search for },] and replace with }]

JSON Output

[{
	"label": "blue",
	"value": 18
}, {
	"label": "red",
	"value": 20
}, {
	"label": "pink",
	"value": 4
}, {
	"label": "yellow",
	"value": 18
}, {
	"label": "green",
	"value": 21
}, {
	"label": "white",
	"value": 25
}, {
	"label": "black",
	"value": 15
}, {
	"label": "violet",
	"value": 12
}, {
	"label": "brown",
	"value": 13
}, {
	"label": "silver",
	"value": 18
}]
Function References

Here as some of the function references that were used in this article, take a look at the links for fine detail of the functions themselves.

Interesting Links

There you have it, four ways on how to handle trailing commas when using while loops. If you have any great solutions, let me know in the comments and I will be sure to add them to this post.

5 Ways to Remove Trailing JSON Comma In While Loop PHP
Posted in PHP

You May Also Like

Leave a Reply

Your email address will not be published.