0

How to remove the last comma of array? currently the result is "apple,orange,papaya,"

i wan the result is "apple,orange,papaya"

for($i = 0; $i < $count; $i++) { 
        $message.= " ".$Cbox[$i].", ";}
Jt Tan
  • 165
  • 2
  • 12
  • 1
    Search stackoverflow question before asking. Real duplicate of https://stackoverflow.com/questions/15408691/how-to-remove-last-comma-from-string-using-php – Mawia HL Jun 12 '18 at 02:53
  • 3
    Possible duplicate of [How to remove last comma from string using php?](https://stackoverflow.com/questions/15408691/how-to-remove-last-comma-from-string-using-php) – Chris Jun 12 '18 at 02:55

3 Answers3

2

You can use rtrim() for this.

$trimmed_message = rtrim($message, ",");

A possible alternative would be to add each item to an array, and then implode() it afterwards. For example,

$message_items = [];

for($i = 0; $i < $count; $i++) { 
   $message_items[] = $Cbox[$i];
}

$message = implode(", ", $message_items);
Chris
  • 4,664
  • 3
  • 42
  • 79
0

use join() function

 $message = join(",",$Cbox);

or use implode() function

 $message = implode(",",$Cbox);
Saurabh Mistry
  • 11,077
  • 4
  • 41
  • 64
0

U can use rtrim() and remove the last , from the string

Ex : rtrim($message,', ');
Asif vora
  • 2,562
  • 3
  • 11
  • 26