我可以在PHP中使用生成的变量名吗?
我有一堆要添加到表单中的值.目前,该表格有11行,但将来可能会更大.我可以轻松地将所有值添加在一起,例如:
I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add all the values together with something like:
$total = $value1 + $value2 + ... + $value11;
我要加在一起的所有值都来自HTML
表单.我想避免使用javascript.
All the values I want to add together are coming from an HTML
form. I want to avoid javascript.
但是,我要避免手动进行操作,尤其是当它变得更大时.这是我尝试使用循环将所有值加在一起的尝试,但是它返回未定义的变量"错误(这只是一些测试代码,可以尝试这一点):
But, I want to avoid having to manually do it, especially if it grows much larger. This is my attempt at adding all the values together using a loop but it returns an "undefined variable" error (it is just some test code to try out the idea):
<?php
$tempTotal = 0;
$pBalance1 = 5;
$pBalance2 = 5;
$pBalance3 = 5;
for ($i = 1 ; $i <= 3 ; $i++){
$tempTotal = $tempTotal + $pBalance.$i;
}
echo $tempTotal;
?>
我想在PHP中做些什么吗?
Is what I want to do possible in PHP?
for ($i = 1 ; $i <= 3 ; $i++){
$varName = "pBalance".$i;
$tempTotal += $$varName;
}
这将做您想要的.但是,您确实可以考虑将数组用于此类操作.
This will do what you want. However you might indeed consider using an array for this kind of thing.