Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php Undefined Offset in simple function()

I'm not sure why I am getting an Undefined Offset Notice on this:

<?php 

$numbers = array('1','2','3');
$total = 0;

for($i=0;$i<=sizeof($numbers); $i++) {
    $total += $numbers[$i];
    echo $total;
}

?>

Output:

136 Notice: Undefined offset: 3 in E:\php\arrays\array_1.php on line 17 6

like image 458
OldWest Avatar asked Jul 14 '11 18:07

OldWest


2 Answers

Your array has three elements at index 0, 1 and 2. There is no element with index 3.

Your loop should stop before it hits that...

for($i=0;$i<sizeof($numbers); $i++) {
}

Also, checkout array_sum, which might be what you're wanting anyway...

$total=array_sum($numbers);
like image 111
Paul Dixon Avatar answered Sep 20 '22 13:09

Paul Dixon


You should loop to < the size of the array, not <=.

for($i=0;$i<sizeof($numbers); $i++) {
like image 36
Dogbert Avatar answered Sep 20 '22 13:09

Dogbert