In JavaScript there is this, +=
to add values after those that have already been added.
What I want to do is forEach
an array that adds 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 any equivalence in PHP ?
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 "
}
unset($valor);
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 hand side to the argument on the left hand 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 would be like this:
Departure:
Another possibility
In the specific case of arrays, you can use
implode
which serves precisely to join elements of an array into a single string .implode
receives two parameters: the first is the value to be pasted to 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:
" "
:Departure:
It's called concatenation 1 , and it's done with the dot
.
Example:
For what you say, it
foreach
would be something like the following:Grades:
Yes, there is a way similar to
+=
, it would be:The
trim
to remove whitespace from the end of the loop, so it's optional.