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?
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
foreachto iterate over the array.As a side note regarding the use of
for, it is less efficient to putsizeof()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.