0

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;
1
  • Can't you do foreach($articletemplateAr as $article) or am I missing something? Commented Mar 8, 2016 at 22:37

2 Answers 2

1

Use this code:

$article = '';
foreach($articletemplateAr as $item) {
    $article .= $$item;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Got my vote because this is cleaner than variable variables. An allows you to insure that you're actually using the intended key/value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.