Question: I am trying to generate a JSON file from PHP. So far I have the following output:

```
"students":[
    {"name": "John"},
    {"name": "Alex"},
    {"name": "Siri"},
]

```

There is a comma after each student, when I clearly have to remove the final comma. Normally I would perform a while loop with an if statement. However, my database structure makes this situation different. 

My PHP code looks like so:

```
    while ($getschools = $schools->fetch_assoc()){
        $findschools = $dbcon->query("SELECT * 
            FROM school_".$getstate['texas']."
            WHERE students = '".$studentGPA['best']."'");       
        while ($beststudents = $findschools->fetch_assoc()){
            $jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
        }
    } 

```

The code might have a few missing parts, but hopefully the context is clear. I am using php variables from previous fetch requests to acquire data from multiple tables. 

In my example there are multiple tables corresponding to the schools in Texas. I am getting the firstnames of every student from those multiple schools (or tables). I am attempting to apply this information to a JSON output. 

The `$jsonfield` line shows the loop portion of my code. I am trying to figure out how to implement a code like this in my example:

```
$i = 0;
$countstudents = $getschools->num_rows;
if ($i < $countstudents){
$jsonfield.=',';
} 

```

This way my commas are only applied to the parts of my data that are not the final iteration of my loop.

Answer: 
You have two options:

**Method 1:** [`rtrim`](http://php.net/rtrim)

Use `rtrim($jsonfield, ',')`

**Method 2:** [`implode`](http://php.net/implode)

Add to `$jsonfield` as array - `$jsonfield[]=....` and then use `implode(',', $jsonfield)`.

---

**Important:**

More than these, why do you want to generate JSON using loop? You can use [`json_encode`](http://php.net/json_encode) function.
```
 while ($getschools = $schools-            >fetch_assoc()){ 
 $findschools = $dbcon->query("SELECT *     FROM school_".$getstate['texas']." WHERE      students = '".$studentGPA['best']."'"); 
   while ($beststudents = $findschools->fetch_assoc()){
  $jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
 $i = 0; 
 $countstudents = $getschool->num_rows;                  
if($i+1 < $countstudents){  //if next index is    smaller than the count then add comma else don't and loop will be terminated
    $jsonfield.=','; 
      }
   }
 }

```