How to combine all elements in an array with a comma?

I know that this question is not in doubt in many cases. Although I can find a solution. So forgive me if this is easy.

The question is how to access the while loop.

eg.

    while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
            $c = $countByMonth["COUNT(id)"];
            echo $c . "," ; 
        }

How to manage a single while loop value with a comma, but of course I don't want the comma to be at the end of the value.

Thank you in advance for your help :)

+3
source share
6 answers

You can:

1) Create a line and delete the last character:

$c = '';
while ($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c .= $countByMonth["COUNT(id)"] . ',';
}

$c = substr($c, 0, -1);
echo $c;

2) Create an array and use implode()

$c = array();
while ($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c[] = $countByMonth["COUNT(id)"];
}

echo implode(',', $c);

. , : SELECT COUNT(id) as count FROM .... $countByMonth['count'], IMO.

+6

1:

$isFirst = true;
while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c = $countByMonth["COUNT(id)"];
    if ($isFirst) {
        $isFirst = false;
    } else {
        echo = ', ';
    }
    echo $c; 
}

implode() . , , // - "," (SO , - ):

$list = '';
while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c = $countByMonth["COUNT(id)"];
    $list .= $c . ', '; 
}
echo substring($list, 0, -2); // Remove last ', '

( , implode(). .)

1 . .

+5

:

$arr = array();
while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
   $arr[] = $countByMonth["COUNT(id)"];
}

echo implode(', ',$arr);
+3

rtrim ($ c, ',')

+2

Although I think the implode solution is probably best in situations where you cannot use implode, think about the main algorithm differently. Instead of "how can I add a comma for every item except the last?" ask yourself: "How to add a comma before each element, but first?"

$str = '';
$count = count( $array );
if( $count ) {
  $i = 0;
  $str = $array[$i];
  $i++;
  while( i < $count ) {
    $str .= ','.$array[$i];
    $i++;
  }
}

If you "shift" the first element, you can use the foreach loop:

$str = '';
if( count( $array ) ) {
  $str = array_shift( $array );
  foreach( $array as $element ) {
    $str .= ', '.$element;
  }
}
0
source

Ty is:

int count;//

while(i)
{
    count=i;
}
-2
source

Source: https://habr.com/ru/post/1765285/


All Articles