Put a comma between words

-3

Colleagues.

I am bringing the result of a dynamic field from which I capture as follows:

$c = 0;
    foreach($xml->avaliacao->respostas as $listar => $valor) {
      $respostas = $_POST["respostas"][$c];
$c++;    
}

With this he brings me:

  

A B C D

I would like to put a comma between the results.

  

A, B, C, D

I know implode does this, but how would I use it?

    
asked by anonymous 15.05.2016 / 23:35

1 answer

2

In your case, $respostas will always be the last element - in case D - because there is a rewrite of the $respostas variable. The first loop contains A , in the second it changes to B ... so on until the last.

Use $respostas as array , so each $_POST["respostas"][$c] will contain an index in the array. Then just use implode to join the array with the right commas.

I've done an example in Ideone , the output is Resposta A, Resposta B, Resposta C, Resposta D . Disregard the array's, they are just for illustration of implode usage.

$c = 0;
$POST = array( 'Resposta A' , 'Resposta B' , 'Resposta C' , 'Resposta D' );

foreach( array( 'A' , 'B' , 'C' , 'D' ) as $listar => $valor)
{
    $respostas[] = $POST[$c];
    $c++;    
}

echo implode( ', ' , $respostas );
    
16.05.2016 / 02:21