tirycm
tirycm

Reputation: 11

PHP variable variable name

I need to use dynamic variable names to create an article template:

 $templatesAr = array("intro","paragraphs","image","conclusion","h2");
 $intro = "Intro";
 $paragraphs = "Paragraphs";
 $image = "image.png";
 $conclusion = "Conclusion";
 $h2 = "Heading";

$articletemplateAr = array("h2", "intro", "image",
    "h2", "paragraphs", "h2", "conclusion");`

How to echo $article in order from $articletemplateAr:

$article = $h2 . $intro . $image . $h2 . $paragraphs . $h2 . $conclusion;

Upvotes: 0

Views: 42

Answers (2)

Barmar
Barmar

Reputation: 781068

PHP variable variables are documented here. You can use ${$articletemplateAr[$i]} to access the variable whose name is in the array element.

However, almost any time you find yourself wanting variable variables, a better approach is to use an associative array.

$values = array(
    'intro' => "Intro",
    'paragraphs' => "Paragraphs",
    'image' => "image.png",
    'conclusion' => "Conclusion",
    'h2' => "Heading"
);

Then you can use $values[$articletemplateAr[$i]].

The reason this is better is because the you can't inadvertently access unintended variables, you're limited to the elements in the array. This is especially important if the elements of $articletemplateAr come from an external source.

Upvotes: 1

alexander.polomodov
alexander.polomodov

Reputation: 5534

Use this code:

$article = '';
foreach($articletemplateAr as $item) {
    $article .= $$item;
}

Upvotes: 1

Related Questions