PHP: increment name of variable in a for loop

爱⌒轻易说出口 提交于 2019-12-12 05:26:06

问题


The for loop fails because "$" is an invalid variable character:

<?php 
$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

for ($i = 0; $i < 3; $i++) {
    echo $num$i . "<br>";
}
?>

(I didn't understand this question)


回答1:


$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

for ($i = 1; $i <=3; $i++) {
    $num = 'num' . $i;
    echo ${$num} . "<br>";
}

But using array is simpler:

$nums = array("Number 1", "Number 2","Number 3");
for ($i = 0; $i <3; $i++) {
    echo $nums[$i] . "<br>";
}



回答2:


What you are trying to do is variable variables (but I recommend you to use an array).

Here is how you should do it.

<?php 
$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

for ($i = 0; $i < 3; $i++) {
    echo ${"num".$i} . "<br>";
}



回答3:


Why don't you use an array? Try this-

<?php 
  $num = Array("Number 1","Number 2","Number 3");
  for ( $i = 0; $i< 3; $i++ ){
    echo $num[$i]."<br>";
  }
?>



回答4:


<?php 
$num1 = "Number 1";
$num2 = "Number 2";
$num3 = "Number 3";

for ($i = 1; $i <= 3; $i++) {
    echo ${"num".$i} . "<br>";
}

?>



回答5:


Have a look at this answer: https://stackoverflow.com/a/9257536/2911633

In your case it would be something like

for($i = 1; $i <= 3; $i++){
     echo ${"num" . $i} . "<br/>";
}

But I would recommend you use arrays instead of this method as arrays give you better control.




回答6:


You're asking for variable variables. An example, like this

for ($i=1; $i<=3; $i++) {
    echo ${"num".$i}."<br />";
}

Usage of variable variables can often result in messy code, so usage of an array is often considered better practice.

Should you want to try out an array, you can do it like this.

$number = array("Number 1", "Number 2", "Number 3");

You can then use a foreach-loop to echo it out, like this

foreach ($number as $value) {
    echo $value."<br />";
}

or as you're using, a for-loop

for ($i=0; $i <= count($number); $i++) {
    echo $number[$i]."<br />";
}


来源:https://stackoverflow.com/questions/34695690/php-increment-name-of-variable-in-a-for-loop

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