Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you append strings to variables in PHP? [duplicate]

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; ?> 
like image 316
James Avatar asked Jan 29 '12 03:01

James


People also ask

Can you concatenate strings in PHP?

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 .

What is an efficient way to combine two variables in PHP?

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.

What does += mean in PHP?

The + operator is the addition operator. += will add numeric values.

What is string interpolation PHP?

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.


1 Answers

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>'; 
like image 79
Jeremy Avatar answered Sep 23 '22 20:09

Jeremy