Why does the following code output 0?
It works with numbers instead of strings just fine. I have similar code in JavaScript that also works. Does PHP not like += with strings?
<?php $selectBox = '<select name="number">'; for ($i=1; $i<=100; $i++) { $selectBox += '<option value="' . $i . '">' . $i . '</option>'; } $selectBox += '</select>'; echo $selectBox; ?>
Prepend and Append Strings in PHPYou can use the concatenation operator . if you want to join strings and assign the result to a third variable or output it. This is useful for both appending and prepending strings depending on their position. You can use the concatenating assignment operator .
The concatenate term in PHP refers to joining multiple strings into one string; it also joins variables as well as the arrays. In PHP, concatenation is done by using the concatenation operator (".") which is a dot.
The + operator is the addition operator. += will add numeric values.
Variable interpolation is adding variables in between when specifying a string literal. PHP will parse the interpolated variables and replace the variable with its value while processing the string literal.
This is because PHP uses the period character .
for string concatenation, not the plus character +
. Therefore to append to a string you want to use the .=
operator:
for ($i=1;$i<=100;$i++) { $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; } $selectBox .= '</select>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With