Abdullah Siddique - 1 year ago 74
PHP Question

# Range values to be calculated in PHP Loop

I need to calculate if avg is > 7.75 means Heavy else No.

What the concern is that.

Need to calculate that from \$x to \$y range of all numbers comes int.

But i was able to get one Avg only not sure what to do to get all numbers Average values and store in Array comes in that range.

``````    function heavyDecC (\$x,\$y)
{

for(\$i=\$x;\$i<=\$y;\$i++)
{
\$numb = \$i;
\$numleng = strlen((string)\$i);
\$int = 0;
for(\$j=0;\$j<\$numleng;\$j++)
{

\$int = \$int + (\$numb % 10);
\$numb = (int)\$numb / 10;
}
\$avg = 0.00;
\$avg = round(\$int/\$numleng,2);
if(\$avg>7)
{
\$isHeavy = "Yes";
}
else
{
\$isHeavy = "No";
}

return \$result[] = array(\$i,\$avg,\$isHeavy);
}
}
``````

Here is a simple solution

``````<?php

\$results = heavyDecC(2685, 5875);

// Display results like this
foreach (\$results as \$id){
echo "--------------------------<br/>";
foreach(\$id as \$key => \$val){
echo \$key . " - " . \$val . "<br />";
}
}

function heavyDecC (\$x,\$y) {

for(\$i=\$x; \$i<=\$y; \$i++){
\$num = \$x;
\$isHeavy = "No";
\$num_length = strlen((string)\$num);
\$array  = array_map('intval', str_split(\$num));
\$sum = array_sum(\$array);
\$average = (\$sum / \$num_length);

if(\$average > 7){
\$isHeavy = "Yes";
}else {
\$isHeavy = "No";
}

\$newdata =  array (
'Number' => \$num,
'average' => \$average,
'is_heavy' => \$isHeavy
);

\$md_array[\$i]= \$newdata;
\$x++;

}

return \$md_array;
}

?>
``````

Results like this

``````--------------------------
Number - 2991
average - 5.25
is_heavy - No
--------------------------
Number - 2992
average - 5.5
is_heavy - No
--------------------------
Number - 2993
average - 5.75
is_heavy - No
--------------------------
Number - 2994
average - 6
is_heavy - No
--------------------------
Number - 2995
average - 6.25
is_heavy - No
--------------------------
Number - 2996
average - 6.5
is_heavy - No
--------------------------
Number - 2997
average - 6.75
is_heavy - No
--------------------------
Number - 2998
average - 7
is_heavy - No
--------------------------
Number - 2999
average - 7.25
is_heavy - Yes
--------------------------
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download