How can I print $title1 $title2 $title3… using a for loop in PHP

若如初见. 提交于 2019-12-24 00:56:29

问题


I want to print these variables using a for loop:

<?php
$title1 = "TEXT1";
$title2 = "TEXT2";
$title3 = "TEXT3";
$title4 = "TEXT4";
$title5 = "TEXT5";

for ($i = 1; $i <= 10; $i++) {    
  echo "$title".$i;   // I want this: TEXT1 TEXT2 TEXT3 TEXT4 TEXT5
}
?>

回答1:


To do exactly what you want, create a new variable containing the name of the variable you want to use, and then use it as a variable variable, like this:

$varname = "title$i";
echo $$varname;

However, the more correct way to do this is to use an array, instead of ten different variables.

$titles = array(
    "TEXT1",
    "TEXT2",
    "TEXT3",
    "TEXT4",
    "TEXT5"
);

for ($i = 0; $i < count($titles) - 1; $i++) { // notice that we're starting at 0 instead of 1
    echo $title[$i];
}

This is faster, cleaner and can often be more secure.




回答2:


You can wrap the string in {}. This tells PHP to use that string as a variable name.

for ($i = 1; $i <= 10; $i++) {  
  echo ${'title'.$i};
}


来源:https://stackoverflow.com/questions/7296381/how-can-i-print-title1-title2-title3-using-a-for-loop-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!