How to concatenate String within a repeat loop?

Asked

Viewed 2,441 times

6

I need to put some values together string.

How do I concatenate values into one string with a loop of repetition.

Example:

for($c=0; $c < $tam; $c++){
    //concatenar sempre o valor
    $minhastring = $valor[$c].',';
}

I mean, I need that every time I enter the loop the variable $mihastring concatenate the values so that it stays:

 $minhastring = $valor[0].','.$valor[1].','.$valor[2].','.$valor[3].',';
  • You want to repeat $valor a number of times? Or that variable is wrong there?

  • Yes, actually this variable $value is dynamic, because it comes from an array...here is $value[$c]

  • every time you enter the loop its value is different....

5 answers

6


I made the first form following the example put in the original question, repeating the value. I doubted it was this, but I answered it anyway. There are simpler ways to do this.

The second is the way to do what you really want, according to the comments and issue of the question. And the third is the simplified way to get the same result.

//solução baseada na pergunta original
$tam = 4;
$minhastring = '';
$valor = 'teste';
for ($i = 0; $i < $tam; $i++) $minhastring .= $valor . ',';
$minhastring = substr($minhastring, 0, -1);
echo $minhastring . "\n";
//solução para a pergunta real
$minhastring = '';
$valor = Array('teste0', 'teste1', 'teste2', 'teste3');
$tam = count($valor); 
for ($i = 0; $i < $tam; $i++) $minhastring .= $valor[$i] . ',';
$minhastring = substr($minhastring, 0, strlen($minhastring) - 1);
echo $minhastring . "\n";
//a mesma solução com função pronta - recomendada
$minhastring = implode($valor, ",");
echo $minhastring;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

4

If the variable is an array, and you want to delimit the elements by commas you can use only one implode().

echo implode(',', $valor);

2

Use the function str_repeat for that reason:

$valor = 'palavra,';              // a cadeia de caracteres que será repetida
$string = str_repeat($valor, 3);  // geramos uma nova cadeia com a quantidade de repetições como parâmetro
$string = substr($string, 0, -1); // tiramos a vírgula ao final da cadeia gerada

1

Replace the operator = for .=

for($c=0; $c < $tam; $c++){
    //concatenar sempre o valor
    $minhastring .= $valor[$c] . ',';
}

0

You can concatenate each loop with the operator .=

$str = '';

for($c=0; $c < $tam; $c++){
    $str .= $valor[$c] . ', ';
}

You’ll also need to remove the last comma

substr(str, 0, -1);

Browser other questions tagged

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