Can you append strings to variables in PHP?

James picture James · Jan 29, 2012 · Viewed 187.5k times · Source

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;
?>

Answer

Jeremy picture Jeremy · Jan 29, 2012

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>';