Jump to content

Unable to remove the comma at the last value


genzedu777

Recommended Posts

Hi guys,

 

Currently my result displayed a 'comma' at the end

 

Lower Primary

English, Math, Science, Chinese,

 

How do I remove the comma which is bold in red? Thank you so much

 

My code

while($row3 = mysqli_fetch_array($data3)) {
         if ($row3['level_id'] == 2) {
            echo ''.$row3['subject_name'].', ';
         }
      }

There are several different ways you could do this -

 

1) Use GROUP_CONCAT() in your query to return the list of values the way you want,

 

2) Echo the ', ' before each value, except on the first pass through the loop,

 

3) Put the values into an array and use implode() to form the list of values,

 

4) Concatenate the values into a string and then trim the extra ', ' off of the end of the string.

Thanks PFMaBiSmAd.

 

Hey CyberRobot!

It works! How did you do it

 

Can you explain the code briefly? I dont quite understand how it works.

 

How did you take away the ',' at the end?

 

$separator = '';
while($row3 = mysqli_fetch_array($data3)) {
   if($row3['level_id'] == 2) {
      echo $separator.$row3['subject_name'];
      $separator = ', ';
   }
}

 

That code is an implementation of choice #2 on the list of possible ways to do this.

 

Can you not look at that code and step through what it is doing and see that it is setting $separator to an empty string before the first pass through the loop so that nothing will be echoed before the first value. It then sets $separator to the actual separator value after the first value has been echoed so that the remainder of the values will have the ', ' separator.

First we created a variable called "$separator" and made sure it was blank.

 

$separator = '';

 

 

Then in the loop, we display whatever "$separator" holds along with the "subject_name". Note that the first time through the loop "$separator" will be blank. Every other time it will contain ', ' which is assigned after the echo statement.

 

...
echo $separator . $row3['subject_name'];
$separator = ', ';
...

 

 

Hopefully that makes sense, let me know if it doesn't.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.