Youiee
Youiee

Reputation: 43

Removing last comma from code?

I am trying to remove the last comma so that it will look like

1,2,3 instead of 1,2,3,

Here is what I have so far;

<?php
    include_once 'header.php';
 ?>
<div id="content">
    Lesson on arrays<br />
    <?php
        $nums = array(0, 1, 2, 3);
        echo "My 1st array =";
        foreach ($nums as $value) {
        echo rtrim($value,",");
        }
?>
</div>
<?php
    include_once 'footer.php';
?>

Currently with the rtrim command in I am getting back

My 1st array =0123

Thanks for any help

Upvotes: 0

Views: 93

Answers (6)

pravindot17
pravindot17

Reputation: 1273

You can use more generic way like following, here comma is attached from second element onwards:

implode is the quickest way to achieve this as explained in previous answer but if you are using loop then use below code:

<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";

$comma = '';
foreach ($nums as $key => $value) {
    echo $comma . $value;
    $comma = ',';
}
?>

Upvotes: 0

sibabrat swain
sibabrat swain

Reputation: 1368

You have two ways you can do with

<?php 
            $string = "";
            $nums = array(0, 1, 2, 3);
            echo "My 1st array = ";

            foreach ($nums as $value) {
                $string .= $value.",";
            }
            print_r(rtrim($string,','));
?>
Or

<?php 

 $nums = array(0, 1, 2, 3);
 $string_by_implode = implode(',',$nums);
 echo "My 1st array = " . $string_by_implode;

?>

Upvotes: 0

Elias Gomes
Elias Gomes

Reputation: 21

Why to use foreach loop when you can do it without the loop, by using implode(). implode() function returns a string separated by a "seperater" from the elements of an array.

$nums = array(0, 1, 2, 3); 

echo "My 1st array = "; 

$str=implode(",",$nums);

echo $str;

This will give you the output as My 1st array = 0,1,2,3

Upvotes: 1

Andreas
Andreas

Reputation: 23958

If you must use that setup then use the $key in the foreach to determine if there should be a comma or not.

$nums = array(0, 1, 2, 3);
echo "My 1st array =";

foreach ($nums as $key => $value) {
    if($key !=0) echo ",";
    echo $value;
}

https://3v4l.org/kKKg1

Upvotes: 0

Yasin Patel
Yasin Patel

Reputation: 5731

Instead of for loop you can directly use implode function.

   <?php
       $nums = array(0, 1, 2, 3);
       echo "My 1st array =";
       echo implode(',',$nums);
  ?>

Edit : if you want foreach loop

<?php
         $nums = array(0, 1, 2, 3);
         echo "My 1st array =";
         $str='';
         foreach ($nums as $value) {
          $str.= $value.",";
         }
         echo rtrim($str,',');
 ?>

Upvotes: 4

Siva Ganesh
Siva Ganesh

Reputation: 1445

Try this

$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');

Output

planes,trains,automobiles

Upvotes: 2

Related Questions