tags:

views:

33

answers:

4

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]; ?></option>
                          <?php } ?>

     </select> 

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

+1  A: 

It should be <. Or use a foreach loop:

foreach($datearray as $month)
{
...
}
Matthew Flaschen
A: 

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

Jonathan Kuhn
+1  A: 

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.

Alex JL
+1  A: 

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 foreach($datearray as $date): ?>
<?php echo $date;?>
<?php endforeach; ?>
ZJR
+1 for introducing the alternative syntax.
Felix Kling
Oh...some people hav so may solutions to a problem. PHP experts.
Zacky112