How to add strings in PHP? That is "+ =" from JavaScript


In JavaScript there is this, += to add values ​​after those that have already been added.

What I want to do is a forEach of an array that forEach the elements of the array to a string.

In this way you can add strings as it was done in JavaScript but in PHP .

Is there an equivalency in PHP ?


$numeros = array("uno ","dos ","tres ");
$numerosencadena = "";
foreach ($numeros as $valor) {
    // Aquí necesito ir añadiendo los valores en $numeroscadena
    // para que quede algo así $numeroscadena = "uno dos tres "

In JavaScript it would be something like this:

var numeros = [];
var numeroscadena;

numeros.forEach(valor => {
    numeroscadena+= valor;


In PHP the equivalent you're asking about is this:. .= And it's called the assignment operator on concatenation , which adds the argument on the right side to the argument on the left side. Of course, the variable must exist before using it, you must take care of that or your error log will be filled with PHP Notice: Undefined variable messages, although it will work the same, do not use the variable without first declaring it empty or with a desired initial value.

In the example that you put the code it would be like this:

$numeros = array("uno ","dos ","tres ");
$numerosencadena = "";
foreach ($numeros as $valor) {
    // Aquí necesito ir concatenando los valores en $numeroscadena
    //para que queda algo así $numeroscadena = "uno dos tres "
    $numerosencadena .=$valor;

echo $numerosencadena;


uno dos tres

Another possibility

In the specific case of arrays you can use implode which serves precisely to unite elements of an array in a single chain .

implode receives two parameters: the first is the value that will be pasted at the end of each value in the array, and the second is the array itself.

In this case, one line of code would be enough to do what you want. Here you indicate that you want each value of the array separated by a blank space: " " :

$conImplode = implode(" ", $numeros);
echo $conImplode;


uno dos tres
Scroll to Top