Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined offset notice when looping through arrays in php

Tags:

arrays

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

     </select> 

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

like image 884
user225269 Avatar asked Dec 28 '22 10:12

user225269


1 Answers

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.

like image 104
JAL Avatar answered Jan 14 '23 13:01

JAL