将文字与变量串联在一起?

时间:2019-05-24 22:59:54

标签: php

我正在尝试用循环创建HTML代码的小部分。在循环中,我想在下面的简化代码中使用$start_intro_headline_X的每个文本值。我该怎么解决?

$start_intro_headline_0 = "This is the first headline";
$start_intro_headline_1 = "This is the second headline";

$intro_sections ="";

for ($x = 0; $x <= 4; $x++) {
$intro_sections .= "<h2>{$start_intro_headline_{$x}}</h2>"; <-- THIS LINE IS THE PROBLEM!
} 

$pageContent = <<<EOD
$intro_sections
EOD;

2 个答案:

答案 0 :(得分:2)

尽管我认为其他答案可行,但避免动态变量会更安全。使用数组来保存您的值:

$start_intro_headline = [
  "This is the first headline",
  "This is the second headline"
];

$intro_sections ="";
$total = count($start_intro_headline);
for ($x = 0; $x < $total; $x++) {
  $intro_sections .= "<h2>{$start_intro_headline[$x]}</h2>";
} 

echo $intro_sections;

这样,您将来不必创建新变量,只需向数组添加新值。这是how it may go wrong to use dynamic variables的示例。

答案 1 :(得分:1)

您需要将变量的名称作为字符串分配给另一个变量,然后将其用作变量变量。我知道这听起来很混乱,所以只看代码即可:)这是代码说明:

$start_intro_headline_0 = "This is the first headline";
$start_intro_headline_1 = "This is the second headline";

$intro_sections ="";

for ($x = 0; $x <= 1; $x++) {
  $var = 'start_intro_headline_'.$x;
  $intro_sections .= "<h2>{$$var}</h2>"; // Note that it's $$var, not $var
} 

echo $intro_sections;

echo将产生<h2>This is the first headline</h2><h2>This is the second headline</h2>