Home > Mobile >  Arrаy and string
Arrаy and string

Time:11-21

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. ', ';
}

CodePudding user response:

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)
?>

CodePudding user response:

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 ',';
    }
}
  •  Tags:  
  • php
  • Related