Place comma between words

Asked

Viewed 400 times

-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 that he brings me:

A B C D

I’d like to comma between the results.

A, B, C, D

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

1 answer

2


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

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


I made an example at Ideone, the output is Resposta A, Resposta B, Resposta C, Resposta D. Disregard the array’s, they are only for illustration of the use of implode.

$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 );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.