82

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;
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James
  • 2,233
  • 4
  • 20
  • 30
  • [Reference for PHP operators](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Charles Sprayberry Jan 29 '12 at 03:31
  • 1
    Is this question really a duplicate? The question asks for appending a string in a special case with a further more specific question about the output of the code. – Henrik Jan 21 '20 at 14:03

3 Answers3

162

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>';
Jeremy
  • 1
  • 85
  • 340
  • 366
22

In PHP use .= to append strings, and not +=.

Why does this output 0? [...] Does PHP not like += with strings?

+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.


More about operators in PHP:

Henrik
  • 2,771
  • 1
  • 23
  • 33
  • `$selectBox = '';` Expands to `$selectBox = '';` PHP converts strings to `0` if they don't at least begin with numbers. Hence `0+0` – John Nov 01 '21 at 07:25
2

PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation.

<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>
Ali Haider
  • 21
  • 4