Search code examples
phpvariable-names

Is there a shorter way to evaluate $t1 + $t2 + $t3 +... + $t24 == 0 in PHP?


I have 24 consecutively numbered variables whose sum I need to evaluate:

if($t1 + $t2 + $t3 + $t4 + $t5 + $t6
   + $t7 + $t8 + $t9 + $t10 + $t11 + $t12
   + $t13 + $t14 + $t15 + $t16 + $t17 + $t18
   + $t19 + $t20 + $t21 + $t22 + $t23 + $t24
   == 0) { /* do stuff */ }

Is there some way to do this without listing every variable?

The following works but still seems unnecessarily complicated:

$sum = 0;
for ($i = 1; $i <= 24; $i++) {
    $sum = $sum + ${"t" . $i};
}
if($sum == 0) { /* do stuff */ }

Solution

  • php supports special naming, to indicate that multiple fields on form should be mapped into array on php side (https://www.php.net/manual/en/faq.html.php#faq.html.arrays)

    so, in html:

    <form>
    <input id="a1" name="a[]">
    <input id="a2" name="a[]">
    <input id="a3" name="a[]">
    </form>
    

    then in php you can use

    $sum = array_sum($_REQUEST['a']);