我可以在PHP中使用生成的变量名吗? [英] Can I use a generated variable name in PHP?

查看:64
本文介绍了我可以在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.

这篇关于我可以在PHP中使用生成的变量名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆