Samadhan Gaikwad Samadhan Gaikwad - 2 months ago 19
PHP Question

Calculate %change from array values in php

I have below code that creates array:

$query = $conn->query("select step1 FROM workflow1 ORDER BY id DESC limit 4;");

$array = Array();
while($result = $query->fetch_assoc()){
$array[] = $result['step1'];
}

print_r($array);


Present Output: Array ( [0] => 1 [1] => 2 [2] => 52 [3] => 10 )

How can I find percentage change in array values? i.e. what I want is

Desired output: ((1-2)/2) -> -50%, ((2-52)/52) -> -96.15% and so on. I going to put it in html table.

Answer Source

Try this one:

$array = [1, 2, 52, 10];
$change = [];
foreach($array as $key=>$value){
  if(count($array) - 1 > $key) {
    $prev = $array[$key];
    $next = $array[++$key];    
    $percent_key = "((".$prev."-".$next.")/".$next.")";    
    $percent_value = (($prev-$next)/$next)*100;
  }
 $change[$percent_key] = $percent_value;
}
print_r($change);

Output:

Array ( [((1-2)/2)] => -50 [((2-52)/52)] => -96.153846153846 [((52-10)/10)] => 420 )