Forum Moderators: coopster
-sned
$a = array(1, 8, 5, 7, 12);
foreach($a as $n)
{
if ($p)
{
$b[] = ($n - $p);
}
$p = $n;
}
print_r($b);
...is the logical solution (off the top of my head, not tested).
One optimisation is that with 1000's of elements you could leave out the test for a previous value and then instead shift element 1 off the output array when you've finished...
$a = array(1, 8, 5, 7, 12);
$p = 0;
foreach($a as $n)
{
$b[] = ($n - $p);
$p = $n;
}
array_shift($b);
print_r($b);
for($i=1;$i<count($a);$i++)
..what are the optimisation implications of this? Is count($a) evaluated every itteration, and if so, is it an expensive operation?
If it is you could of course evaluate it once and use a variable instead, but i'm just curious - i've wondered about this before.
I tested each of the 3 methods listed here, in the order listed, on an array of 300,000 items. Each test was done 10 times; here are the times it took for each:
Average / Min / Max times
Test 1: 5.206/ 5.011/ 5.632
Test 2: 6.656/ 4.928/ 12.447
Test 3: 5.634/ 4.804/ 12.028
Chad