Newbie here in PHP programming. I have some question regarding arrays. How can I get the difference between adjacent values in an array?
$value = array(2, 5, 9, 10, 19);
How do I get the difference between the 2 and 5? Then 9 and 5? Then 10 and 9, then 19 and 10? The reason I want to get the difference is to draw a stack graph. And each stack will depend on each difference.
Hi, sorry guys, totally lost on this one. It seems that I can't do it the way I want. Please click here to see the similar stacked graph I want. How do I create a scale for my arrays so that when I plot the stacked graph it will automatically adjust to its value?
Here is the code that I am trying to use.
<?php
$img_width=200;
$img_height=425;
$img=imagecreatetruecolor($img_width,$img_height);
$bar_color=imagecolorallocate($img,0,64,128);
$line_color=imagecolorallocate($img,220,220,220);
imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color);
$value = array(116,160,210,269,325,425);
for ($i = 1, $n = count($value); $i < $n; $i++) {
$diffs[] = $value[$i] - $value[$i-1];
imageline($img,0,$value[$i]-$value[$i-1],$img_width,$value[$i]-$value[$i-1],$line_color);
}
header("Content-type:image/png");
imagepng($img);
?>
I appreciate all your help.
Just use a simple for
loop:
$diffs = array();
for ($i = 1, $n = count($value); $i < $n; $i++) {
$diffs[] = $value[$i] - $value[$i-1];
}
@Gumbo you added $diffs = array(); it has to be $value
<?php
$value = array(2,5,9,10,19);
for ($i = 1, $n = count($value); $i < $n; $i++) {
$diffs[] = $value[$i] - $value[$i-1];
}
echo "<pre>";
print_r($diffs);
echo "</pre>";
?>