在循环中使用静态字符串和计数器变量声明变量
如何在 for 循环内创建可变变量?
这是循环:
for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
}
在这个循环中,我想在每次通过时创建一个变量 $seat ,但它必须像这样递增。第一次通过时应该是 $seat1 = $_POST['seat' + $aantalZitjesBestellen]
,下次通过时: $seat2 = $_POST['seat' + $aantalZitjesBestellen]< /代码>等等。
最后应该是:
$seat1 = $_POST['seat1'];
$seat2 = $_POST['seat2'];
等等。
$_POST 的变量和内容应该是动态的。
How do I create variable variables inside a for loop?
This is the loop:
for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
}
Inside this loop, I would like to create a variable $seat for each time it passes but it has to increment like so. first time it passes it should be $seat1 = $_POST['seat' + $aantalZitjesBestellen]
, next time it passes: $seat2 = $_POST['seat' + $aantalZitjesBestellen]
and so on.
At the end, it should be:
$seat1 = $_POST['seat1'];
$seat2 = $_POST['seat2'];
and so on.
The variable and the content of the $_POST should be dynamic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,除非我遗漏了什么,否则我会使用数组。与使用数组相比,使用诸如
$seat1
、$seat2
等变量往往实用性要低得多,而且要麻烦得多。话虽这么说,请使用以下语法:
最后,PHP 有一个内置函数,用于将数组键提取到符号表中:
extract()
。如果您将extract()
与未经过滤的用户输入(例如$_POST
)一起使用,它会带来巨大的潜在安全问题,因此请谨慎使用。Firstly, I would use an array for this unless I'm missing something. Having variables like
$seat1
,$seat2
, etc tends to have far less utility and be far more cumbersome than using an array.That being said, use this syntax:
Lastly, PHP has an inbuilt function for extracting array keys into the symbol table:
extract()
.extract()
has enormous potential security problems if you use it with unfiltered user input (eg$_POST
) so use with caution.这也将起作用:
This will work as well:
(为了清晰起见,进行了扩展 - 您也许能够写出一句台词)
但是!你真的不应该这样做。 (如果你确实必须这样做,请参阅cletus的答案了解内置的PHP方法它 - 不过,这也被认为是不好的做法。)
重新考虑你的问题并看看数组是否可能是解决方案(我想它会)。这将使检查(例如通过
var_dump()
)和迭代变得更容易,并且不会污染全局变量空间。(Expanded for clarity - you may be able to do a one-liner)
BUT! You really shouldn't do this. (And if you really must, see cletus' answer for the built-in PHP way to do it - this is considered bad practice too, though.)
Reconsider your problem and see if arrays might be the solution (I guess it will). This will make both inspection (via e.g.
var_dump()
) and iteration easier and does not pollute the global variable space.建议使用数组,因为可以更轻松地检查它们。
It's recommended to use arrays, as you can check them easier.
您可以使用 extract 但我不建议您执行您正在尝试的操作去做。
You can use extract but I don't recommended to do what you are trying to do.