问题
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