Can I use a generated variable name in PHP?

前端 未结 9 2163
梦谈多话
梦谈多话 2020-12-11 11:50

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

相关标签:
9条回答
  • 2020-12-11 12:22

    The values you need are posted from a form, right? If so, you could iterate through the keys in the $_POST variable that match your form field's generated names.

    foreach($_POST as $key=>$value)
    {
      if(strpos($key, 'pBalance')===0)
      {
        $final_total += $value;
      }
    }
    
    0 讨论(0)
  • 2020-12-11 12:25
    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.

    0 讨论(0)
  • 2020-12-11 12:26

    In about 99% of all cases involving a PHP generated variable, you are doing The Wrong Thing. I'll just re-iterate what others have said:

    USE AN ARRAY

    0 讨论(0)
  • 2020-12-11 12:34

    Uhm why don't you use an array? If you give the forms a name like foobar[] it will be an array in PHP.

    0 讨论(0)
  • 2020-12-11 12:35

    If you're trying to collect the values of a POST, you should really use an array. You can avoid having to manually piece together such an array by using:

    <input type="text" name="vals[]" value="one" />
    <input type="text" name="vals[]" value="two" />
    

    $_POST["vals"] will then be array("one", "two");

    0 讨论(0)
  • 2020-12-11 12:38

    I would use @unexist's solution.. give the input fields names like:

    <input name="myInput[]" />
    <input name="myInput[]" />
    <input name="myInput[]" />
    ...
    

    Then in your PHP get the sum like this:

    $total = array_sum($_REQUEST['myInput']);
    

    Because of the '[]' at the end of each input name, PHP will make $_REQUEST['myInput'] automatically be an array. A handy feature of PHP!

    0 讨论(0)
提交回复
热议问题