I’m trying to run a PHP script that finds all the numbers divisible by 3 or 5, dumps them into an array, and adds all the values together. However, When I try to run it, I get a number output (I don’t know if it’s correct or not) and several hundred errors. They start out with:
Notice: Undefined offset: 1 in G:\Computer Stuff\WampServer\wamp\www\findthreesandfives.php on line 18
Then the offset number increases by increments of 1-3 (randomly, I haven’t seen a pattern yet). I can’t figure out what’s wrong. Here’s my code:
<?php
function loop($x)
{
$a = array(); //array of values divisible by 3 or 5
$l = 0; //length of the array
$e = 0; //sum of all the values in the array
for ($i=0; $i<=$x; $i++){ //this for loop creates the array
$n3=$i%3;
$n5=$i%5;
if($n3 === 0 || $n5 === 0){
$a[$i]=$i;
$l++;
}
}
for ($v=0; $v<=$l; $v++){ //this loop adds each value of the array to the total value
$e=$e + $a[$v];
}
return $e;
}
echo loop(1000);
?>
Someone please help…
The problem in your code is the following line:
Should be:
This is because the value of
$iis always increasing, so using$ias your pointer will create gaps in the array’s indices.count($a)returns the total number of items in the given array, which also happens to be the next index.EDIT: @pebbl suggested using
$a[] = $i;as a simpler alternative providing the same functionality.EDIT 2: Solving the subsequent problem the OP described in the comments:
The problem seems to be that
$lis greater than the number of items in$a. Thus, usingcount($a)in the for loop should fix your subsequent error.Try replacing:
With: