简体   繁体   中英

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;

Use this code:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM