I'm trying to set up a basic PHP code where it scans through numbers and calculates the total from a certain set of conditions. Here, I'm saying I want to add all the numbers between 100 and 200 that are even and multiples of 5. To do this, i thought I could first put those numbers into an array, then add up the array.
Something like this:
<?php
$total = 0;
$naturalNumber = array();
$naturalNumber[] = $i;
while ($i % 2 == 0 && $i % 5 == 0) {
for($i>=100; $i <=200; $i++) {
$naturalNumber[] = $i;
$total = array_sum($naturalNumber);
}
}
echo "<p>$total</p>";
?>
But error occurs: cannot use [] for reading
, is there any semantic issues here as well?
Your for
loop is incorrect:
for($i>=100; $i <=200; $i++) {
^^
The first argument for for
should be an assignment of a value, you're not doing that, you're just testing if $i
is larger than 100, which makes no sense. $i
was never defined in the first place, so you're effectively trying to iterate (null >= 100) -> 200
-> false -> 200
-> 0 -> 200
.
You want
for($i = 100; $i <=200; $i++) {
^---note this
instead.
Plus the nesting of the while
and for
is also just... weird. Why the while
in the first place? All you need is the for
loop and and if
inside that does the various %
testing.