开发者

undefined offset notice when looping through arrays in php

I have this code that loops through a list and post it in an option tag. But I get an undefined offset notice everytime I try to run it.

<?php $datearray=array('Jan','Feb','Mar'); ?>

<?php for($d=0;$d<=sizeof($datearray);$d++){ ?>
  <select title="mm" name="month" id="month" class=""> 


                          <option><?php echo $datearray[$d]; ?></optio开发者_运维百科n>
                          <?php } ?>

     </select> 

How do I solve this?Is there a better way on doing this?


It's because you are using <= instead of <. The sizeof (count) for an array will always be one more than the number of the highest index. This is because the indexes start at 0 of course, but the count is that actual number - and humans count starting at 1.

You could also use foreach to iterate over the array.

<?php foreach($datearray as $date){ ?>
      <option><?php echo $date; ?></option>
<?php } ?>

As a side note regarding the use of for, it is less efficient to put sizeof() in the for loop condition. This is because PHP calculates the count on each loop. Assigning the sizeof result to a variable and comparing to that works better.


How do you solve it... by learning how to scan your zero-based arrays.

You can't use $index<=$length as a condition.

Use $index<$length, instead.

<?php for($d=0;$d<sizeof($datearray);$d++){ ?>
               ^^^^^

And yes, there's a better way:

<?php foreach($datearray as $date){ ?>

<?php echo $date;?>

<?php } ?>

and an even better one: (PHP endfor/endforeach syntax)

<?php foreach($datearray as $date): ?>

<?php echo $date;?>

<?php endforeach; ?>


It should be <. Or use a foreach loop:

foreach($datearray as $month)
{
...
}


the problem is that if you have an array with 10 elements, it starts at 0. Sizeof will return 10 and the array will have 10 elements, 0 to 9. The last element in the array should be 1 less than the sizeof the array. So the for loop should be: for($d=0;$d<sizeof($datearray);$d++)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜