-4

How to remove comma at the end of an array? Need output: 1,2,3,4,5 and not 1,2,3,4, 5,

I know I can use implode, but is there another way?

$massive = [1, 2, 3, 4, 5];
 
foreach($massive as $items){
echo $items. ', ';
}
Ice time
  • 3
  • 3
  • use function `implode()` https://www.php.net/manual/en/function.implode.php – Jun Pan Nov 21 '22 at 03:21
  • Print comma if you are not at the end (or, alternately, at the beginning, if you print comma before the item). But why would you not use `implode`, since it's right there, the right tool for the job? – Amadan Nov 21 '22 at 03:22
  • 1
    There's a function for this - use it. If you really **can't** use it then explain **why** so that we don't spend time suggesting options that you may also be unable to use. Downvoted, because it's a meaningless question. – Tangentially Perpendicular Nov 21 '22 at 03:25
  • https://3v4l.org/tvY4L .. The most easy solution. – Alive to die - Anant Nov 21 '22 at 04:10

2 Answers2

1

You can use implode and if don't want to use the inbuilt function then use a new variable like this

<?php
$massive = [1, 2, 3, 4, 5];
$str="";
 
foreach($massive as $items){
    $str .= $items.",";
}
echo substr($str,0,-1)
?>
vivek modi
  • 800
  • 2
  • 7
  • 23
0

This pattern shows up frequently. I thought I might offer a generic way to handle it.

$arr = [100, 200, 300, 400, 500, 600];
$out = null;
foreach ( $arr as $a ) {
    // The trick is to output the comma before each element
    // except the first one.
    if ( ! empty($out) ) {
        $out .= ',';
    }
    $out .= $a;
}
// Now I can output the string

What if I wanted to output the data as the loop progresses? Just set a boolean to false then after processing the first element, set it to true.

$arr = [100, 200, 300, 400, 500, 600];
$first = true;
foreach ( $arr as $a ) {
    // The trick is to output the comma before each element
    // except the first one.
    if ( $first ) {
        echo ',';
        $first = false;
    }
    echo $a;
}

Is there another way? Yes.

foreach ( $arr as $a ) {
    // see if it is the first element
    if ( $a == first($arr) ) {
        echo ',';
        $first = false;
    }
    echo $a;
}

Or we can detect the last item and just not output the comma.

foreach ( $arr as $a ) {
    echo $a;
    if ( last($arr) != $a ) {
        echo ',';
    }
}
ryantxr
  • 4,119
  • 1
  • 11
  • 25