开发者

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


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);


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

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


Change your condition from <= to <.

This will add properly:

$total += intval($numbers[$i]);


turnoff html errors

error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('html_errors', 'Off'); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜