Saturday, 15 December 2018

Can you append strings to variables in PHP?




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?




    $selectBox = '';

echo $selectBox;

?>

Answer



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 .= '';
}
$selectBox .= '';


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...