I have a large form, which when submitted to the database, it needs splitting into odd and even (based on their HTML name), so I can perform a calculation on them.
There are 120 total HTML Input
fields, so 60 odd and 60 even.
The for loops
that iterates through them are:
$h=0; $o=0;
for($i=1; $i<=119; $i+=2)
{
$h = $h + Input::get($i);
}
for($i=2; $i<=120; $i+=2)
{
$o = $o + Input::get($i);
}
What I am finding is that the odd number for loop is working correctly, but even though the second loop begins at 2, it is skipping adding that Input::get($i);
and moving onto the 4th input.
If I echo the odd
for loop, it outputs (with all the input values at 1):
for($i=2; $i<=120; $i+=2)
{
echo $i;
echo (",");
$o = $o + Input::get($i);
echo (Input::get($i));
}
2,14,16,18,110,112,114,116,118,
So as you can see, it isn't picking up the '1' value from the 2nd input field.
Any help as to why this is would be greatly appreciated.
You do not need two loops to accomplish this, use the modulo math function to determine if there is a remainder of 0 when dividing by 2 (indicating an even number), try this out:
for($i=0; $i<=120; $i++)
{
if($i%2 == 0) //even
$o = $o + Input::get($i);
else //odd
$h = $h + Input::get($i);
}
You should make a single loop that iterates from 1 to 120. Then test if the counter is odd/even using the modulus operator ($a % $b).
i.e. if $a % 2 = 0 then the value is even else it is odd.