Shristi Shristi - 1 year ago 46
PHP Question

best way to loop calculations in php

i want to calculate two operations with the help of loop. They are already working and providing result i need. But i want them to look more like coding. So if anybody can help them with the help of for in php

$temp_calc = ;

here are two statements.

  1. In first statement length of array is 9.

  2. In second statement length of array is 12.

both statements to be solved in different for loop as they are totally different questions.

$temp_calc = 10*$temp_array[0]+9*$temp_array[1]+8*$temp_array[2]+7*$temp_array[3]+6*$temp_array[4]+5*$temp_array[5]+4*$temp_array[6]+3*$temp_array[7]+2*$temp_array[8];

$temp_calc = 1*$temp_array[0]+3*$temp_array[1]+1*$temp_array[2]+3*$temp_array[3]+1*$temp_array[4]+3*$temp_array[5]+1*$temp_array[6]+3*$temp_array[7]+1*$temp_array[8]+3*$temp_array[9]+1*$temp_array[10]+3*$temp_array[11];

Thanks in advance

Answer Source

for both issues:

$temp_array = array(2,2,2,2,2,2,2,2,2);//sample

function calc_1($temp_array){//first
    $count = count($temp_array)+1;
    foreach($temp_array as $value){
        $total += $count*$value;
    return $total;
function calc_2($temp_array){//second
    foreach($temp_array as $k=>$value){
        $total += ($k%2==0) ? 1*$value : 3*$value;//when is even or odd
    return $total;