How to concatenate String within a loop of repetition?

6

I need to add some values in a string .

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

Example:

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

That is, I need each time that every time I enter the variable $mihastring go concatenating the values so that it stays:

 $minhastring = $valor[0].','.$valor[1].','.$valor[2].','.$valor[3].',';
    
asked by anonymous 22.09.2015 / 13:43

5 answers

6

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

The second is the way to do what you really want, according to the comments and editing 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;

See working on ideone .

    
22.09.2015 / 13:56
3

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

echo implode(',', $valor);
    
22.09.2015 / 14:07
2

Use the str_repeat function to do this:

$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
    
22.09.2015 / 13:56
1

Replace operator = with .=

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

You can concatenate each loop with the .=

$str = '';

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

You will also need to remove the last comma

substr(str, 0, -1);
    
24.10.2018 / 15:13