如何在php中递归地添加数字

如何在php中递归地添加数字,php,Php,我想添加$colnum的最后一位数字,如下所示。请参考代码中的注释 for($c=2;$c<$keynum;$c++){ ... ... $studentcomment = ''; for($col=1;$col<5;$col++){ $colnum="col".$col."_".$c;// this will find col1_2, col2_2, col3_2, col4_2 $colnum= $this->input->post($colnum)

我想添加$colnum的最后一位数字,如下所示。请参考代码中的注释

for($c=2;$c<$keynum;$c++){
...
...
$studentcomment = '';
for($col=1;$col<5;$col++){
    $colnum="col".$col."_".$c;// this will find col1_2, col2_2, col3_2, col4_2 
    $colnum= $this->input->post($colnum);// this will get value from post. 
    //e.g. col11, col12 col13 col14 or col15
    echo "colnum is ";
    echo $colnum; // this will be col12
    echo "<br />";
    $subgrade="";
    $subgrade = substr($colnum,-1);// get the last digit
    if($subgrade<5 AND !empty ($subgrade)){// 5 has no comment so excluded
        echo "subgrade is ";
        echo $subgrade;// this will be 2,3 or 4
        $total="";
        $total += $subgrade;// add all the subgrade to find the total
        echo "<br />";
        echo "Total collaboration marks is ";
        echo $total;
    }

    if(!empty($colnum)){
        $studentcomment .=$this->lang->line($colnum);//output all the comments 
from language file.
    }

}

非常感谢您的帮助。提前谢谢。

您正在重置
for
循环中的
$total
,此处:

$total=""; 

这需要移动到循环之外。代码肯定需要一些清理。

我不确定我是否完全理解您的问题,但如果您希望
$total
包含所有列的总计,则需要删除行
$total=“”,或将其移到循环外。这会在for循环的每次迭代中不断重置总值

$total="";