Can I use a generated variable name in PHP?

前端 未结 9 2164
梦谈多话
梦谈多话 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:39

    The concept you're looking for is called a variable variable (at least it's called that in PHP). Here is the official documentation and a useful tutorial. The syntax for a variable variable is a double dollar sign ($$).

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

    Try

    $varName = 'pBalance' . $i;
    $tempTotal = $tempTotal + $$varName;
    
    0 讨论(0)
  • 2020-12-11 12:46

    You can use an array to store your data, and just loop over it.

    $tempTotal = 0;
    
    $balances[] = 5;
    $balances[] = 5;
    $balances[] = 5;
    
    for  ($i = 0; $i <= count($balances); $i++) {
        $tempTotal = $tempTotal + $balances[$i];
    }
    

    Or for brevity, use a foreach loop:

    foreach($balances as $balance) {
        $tempTotal += $balance;
    }
    
    0 讨论(0)
提交回复
热议问题