5

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?

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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; ?>

1 Comment

Oh...some people hav so may solutions to a problem. PHP experts.
1

It should be <. Or use a foreach loop:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.