3D-kreativ
3D-kreativ

Reputation: 9319

Concatenate text with variable in variable?

I'm trying to create small sections of HTML code with a loop. In the loop I want to take each text value of $start_intro_headline_X in the simplified code below. How can I solve this?

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

Upvotes: 1

Views: 36

Answers (2)

Ibu
Ibu

Reputation: 43850

Although I think the other answer works, it will be safer to avoid dynamic variables. Use an array to save your values instead:

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

This way you don't have to create new variables in the future, only add new values to the array. Here is an example of how it may go wrong to use dynamic variables.

Upvotes: 2

Kevin Kopf
Kevin Kopf

Reputation: 14230

You need to assign the name of the variable as a string to another variable and then use it as a variable variable. I know it sounds confusing, so just see the code :) Here's the code explanation:

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

The echo will produce <h2>This is the first headline</h2><h2>This is the second headline</h2>

Upvotes: 1

Related Questions