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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With