【问题标题】:PHP variable in loop循环中的PHP变量
【发布时间】:2012-03-01 17:04:44
【问题描述】:

我有以下几点:

$textq1 = 'text';
$textq2 = 'more text';

我有一个循环:

for ($i = 1; $i <= 70; $i++) {

    echo "<div>". $textq1." ";

}

现在....我想做的是,在循环中将$textq11 部分设为$i 的值。

这可能吗?

【问题讨论】:

  • 如果你有 $textq = array('text','more text'); 会容易得多而不是 $textq1 = 'text'; $textq2 = '更多文字';
  • @MarkBaker - 是的,在数组中肯定会更容易,但我继承了一大堆代码......

标签: php variables loops for-loop


【解决方案1】:

变化:

echo "<div>". $textq1." ";

收件人:

echo "<div>". ${'textq'.$i} ." ";

【讨论】:

    【解决方案2】:
    for (...)
    {
        echo "<div>{${textq$i}}</div>";
    }
    

    【讨论】:

    • 这将导致Parse error: syntax error, unexpected T_VARIABLE 错误。
    • 是的。如果是 echo "&lt;div&gt;{${"textq$i"}}&lt;/div&gt;"; 会起作用(需要在变量名周围加上引号)。
    【解决方案3】:
    $var = "textq{$i}";
    echo "<div>". $$var." ";
    

    【讨论】:

      【解决方案4】:

      查看 PHP 文档中关于 variable variables 的示例: http://www.php.net/manual/en/language.variables.variable.php#105282

      【讨论】:

        猜你喜欢
        • 2014-05-27
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 2013-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多