PHP变量名称加1 [重复]

时间:2022-10-15 16:22:37

This question already has an answer here:

这个问题在这里已有答案:

I use a loop and 8 variables with almost the same name.

我使用一个循环和8个变量,名称几乎相同。

$date1,$date2,$date3,etc..

Now I want to do in the loop echo $date$i Any idea how to achieve this ?

现在我想在循环中做回声$ date $ i任何想法如何实现这一点?

The PHP loop :

PHP循环:

$i = 1;
while ($i < 8 ) {
echo $date$i;
$i++;
}

2 个解决方案

#1


Usually you'll use an array for that:

通常你会使用一个数组:

$data = array('x', 'y', 'z', 'a', 'b', 'c', '1' , '2');
for($i = 0; $i < 8; $i++) {
    echo $data[$i];
}

However if you for whatever reason need 8 variables (I can't see a reason), you need to do it like this:

但是如果你因为什么原因需要8个变量(我看不出原因),你需要这样做:

for($i = 0; $i < 8; $i++) {
    echo ${"data$i"};
}

#2


As mentioned by others before, a better way to go about this this would be to use arrays. Anyways correct syntax for what you want to do would be

正如其他人之前提到的,更好的方法是使用数组。无论如何,你想要做的语法是正确的

$i = 1;
while ($i < 8 ) {
echo ${"date$i"};
$i++;
}

#1


Usually you'll use an array for that:

通常你会使用一个数组:

$data = array('x', 'y', 'z', 'a', 'b', 'c', '1' , '2');
for($i = 0; $i < 8; $i++) {
    echo $data[$i];
}

However if you for whatever reason need 8 variables (I can't see a reason), you need to do it like this:

但是如果你因为什么原因需要8个变量(我看不出原因),你需要这样做:

for($i = 0; $i < 8; $i++) {
    echo ${"data$i"};
}

#2


As mentioned by others before, a better way to go about this this would be to use arrays. Anyways correct syntax for what you want to do would be

正如其他人之前提到的,更好的方法是使用数组。无论如何,你想要做的语法是正确的

$i = 1;
while ($i < 8 ) {
echo ${"date$i"};
$i++;
}