0

I have these loop statement to generate arrays labeled with z variable. array will be sent to ajax to be displayed in HTML page.

    for($z=0;$z<5;$z++){    
        $billsum = $bills['amount'];
         $bill['$z'] = [$billsum];      
    }

How can I generate arrays such as $bill0,$bill1,$bill2,$bill3,...etc

A.K.
  • 141
  • 1
  • 2
  • 14
  • remove the `'` around $z: `$bill[$z] = $billsum;` (and the [] - or do you really want _another_ nested array in there?) – Jeff Oct 25 '18 at 15:34
  • 1
    you are aware, that $billsum will allways be the same?? – Jeff Oct 25 '18 at 15:38
  • since you accepted an answer below (which is correct) I just wanted to tell you, that it's a very bad idea to have variables named $bill0, $bill1, ... This is what arrays are for! – Jeff Oct 25 '18 at 16:03
  • @Jeff would you please explain. Thx – A.K. Oct 25 '18 at 16:04
  • it's far better and more practical to have an array `$bills` that contains each bill in `$bill[0], $bill[1],..`. (or maybe you want an array with only billsums, then call it `$billsums[1], ..` – Jeff Oct 25 '18 at 16:06
  • @Jeff I understand your words, but I would like to know why it is bad technically? – A.K. Oct 25 '18 at 16:11
  • some reads: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval , https://stackoverflow.com/questions/17343949/variable-variables-bad-practice-to-use, https://stackoverflow.com/questions/17135192/php-how-can-i-create-variable-names-within-a-loop especially https://stackoverflow.com/a/17135494/4830296 – Jeff Oct 25 '18 at 16:31

2 Answers2

2

$z shouldn't be inside quotes.

for($z=0;$z<5;$z++){    
        $billsum = $bills['amount'];
        $bill[$z] = [$billsum];      
}
Alex
  • 4,674
  • 5
  • 38
  • 59
1
for($z=0;$z<5;$z++){    
        $billsum = $bills['amount'];
        ${'bill'.$z} = [$billsum];      
}

So, now you will have arrays like $bill0,$bill1,$bill2,$bill3...

nice_dev
  • 17,053
  • 2
  • 21
  • 35