So I have an array in Php where I have the following values respectively.
$arr = [1,2,0,0,5,6,7,8,9,10,7,5,7,6,4,7,4,6,4,7,1,15,35];
So when I am applying the growth rate formula in this. Some of the values showing NaN and INF. I Know it's happening because of the 0
I put in the array.
So What I need is to replace the NaN, INF values with 0 or something so the values not get skipped.
I tried in many ways. but it doesn't seem to work.
Here is my code :
$growthrate = [];
$arr = [1,2,0,0,5,6,7,8,9,10,7,5,7,6,4,7,4,6,4,7,1,15,35];
for($i=1;$i<count($arr);$i++)
{
$growthrate[] = $arr[$i]/$arr[$i-1];
error_reporting(E_ERROR | E_PARSE);
}
print_r($growthrate);
Here you can see the output I am getting :
Array ( [0] => 2 [1] => 0 [2] => NAN [3] => INF [4] => 1.2 [5] => 1.1666666666667 [6] => 1.1428571428571 [7] => 1.125 [8] => 1.1111111111111 [9] => 0.7 [10] => 0.71428571428571 [11] => 1.4 [12] => 0.85714285714286 [13] => 0.66666666666667 [14] => 1.75 [15] => 0.57142857142857 [16] => 1.5 [17] => 0.66666666666667 [18] => 1.75 [19] => 0.14285714285714 [20] => 15 [21] => 2.3333333333333 )
What can I do to replace the NaN and INF values to ) or anything or make it an exception.
My Answer:
$growthrate[] = 0;
} else {
$growthrate[] = ($arr[$i] - $arr[$i-1]) / $arr[$i-1] * 100;
if(is_nan($growthrate[$i]) || is_infinite($growthrate[$i])){
$growthrate[$i] = 0;
}
}
}
echo "
Rate this post
5 of 5 based on 2884 votesComments