您可以将字符串附加到PHP中的变量吗? [英] Can you append strings to variables in PHP?

查看:66
本文介绍了您可以将字符串附加到PHP中的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码输出0?

Why does the following code output 0?

它适用于数字而不是字符串.我在JavaScript中也有类似的代码,也可以使用. PHP是否不喜欢+ =和字符串?

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

推荐答案

这是因为PHP使用句点字符.进行字符串连接,而不是加号+.因此,要附加到字符串,您要使用.=运算符:

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

这篇关于您可以将字符串附加到PHP中的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆