Shristi - 2 years ago 64
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

``````for(\$i=0;i<something;\$i++){
\$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];
``````

for both issues:

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

function calc_1(\$temp_array){//first
\$total=0;
\$count = count(\$temp_array)+1;
foreach(\$temp_array as \$value){
\$total += \$count*\$value;
\$count-=1;
}
return \$total;
}
function calc_2(\$temp_array){//second
\$total=0;
foreach(\$temp_array as \$k=>\$value){
\$total += (\$k%2==0) ? 1*\$value : 3*\$value;//when is even or odd
}
return \$total;
}
var_dump(calc_1(\$temp_array));//resp1
var_dump(calc_2(\$temp_array));//resp2
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download