I have created the array $numbers
which consists of 45 numbers sorted from smallest to largest, with no number appearing twice:
$numbers = [5, 12, 24, 43, 60, 84, 87, 94, 124, 178, 226, 276, 313, 327, 336, 364, 367 , 368, 383, 399, 403, 434, 505, 539, 545, 582 , 584, 586, 651, 654, 676, 729, 739, 750, 754, 777, 788, 808, 814, 846, 857, 886, 895, 932, 999];
I also define the empty array $differences
:
$differences = [];
and save the amount of elements in $numbers
as the variable $amount
:
$amount = count($numbers);
My goal is to save all differences between the elements of $numbers
in the array $differences
i.e.:
$differences[] = $numbers[1] - $numbers[0];
$differences[] = $numbers[2] - $numbers[1];
etc.
I would like this process to be done more efficiently through the use of a for loop:
for ($i = 1; $i < $amount; $i++) {
$differences[] = $numbers[$i] - $numbers[$i-1];
};
The loop seems to be working fine, however, looking at the content of $differences
one notices that it only has 42 numbers stored in it, not the expected 44. By printing $differences
you can see that it lacks the last two differences.
Since the script seems to be working fine otherwise and the simplicity of the loop does not leave room for many mistakes, I find this malfunction very bizarre.
Does anyone know what the cause of it might be and how it can be fixed?
EDIT: I isolated the part of the script from my question and now it really doesn't show any faults. I presume I made a mistake in some other part.
I ran your code and it outputs 44 results, there's no error here.
$numbers = [5, 12, 24, 43, 60, 84, 87, 94, 124, 178, 226, 276, 313, 327, 336, 364, 367 , 368, 383, 399, 403, 434, 505, 539, 545, 582 , 584, 586, 651, 654, 676, 729, 739, 750, 754, 777, 788, 808, 814, 846, 857, 886, 895, 932, 999];
$amount = count($numbers);
for ($i = 1; $i < $amount; $i++) {
$differences[] = $numbers[$i] - $numbers[$i-1];
};
var_dump($differences);
Result:
array(44) {
[0]=>
int(7)
[1]=>
int(12)
[2]=>
int(19)
[3]=>
int(17)
[4]=>
int(24)
[5]=>
int(3)
[6]=>
int(7)
[7]=>
int(30)
[8]=>
int(54)
[9]=>
int(48)
[10]=>
int(50)
[11]=>
int(37)
[12]=>
int(14)
[13]=>
int(9)
[14]=>
int(28)
[15]=>
int(3)
[16]=>
int(1)
[17]=>
int(15)
[18]=>
int(16)
[19]=>
int(4)
[20]=>
int(31)
[21]=>
int(71)
[22]=>
int(34)
[23]=>
int(6)
[24]=>
int(37)
[25]=>
int(2)
[26]=>
int(2)
[27]=>
int(65)
[28]=>
int(3)
[29]=>
int(22)
[30]=>
int(53)
[31]=>
int(10)
[32]=>
int(11)
[33]=>
int(4)
[34]=>
int(23)
[35]=>
int(11)
[36]=>
int(20)
[37]=>
int(6)
[38]=>
int(32)
[39]=>
int(11)
[40]=>
int(29)
[41]=>
int(9)
[42]=>
int(37)
[43]=>
int(67)
}