Undefined offset notification when navigating through arrays in php

I have this code that goes through a list and publishes it in an options tag. But I get a notification about decreasing undefined every time 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 can i solve this? Is there a better way to do this?

+4
source share
4 answers

This is because you use <= instead of <. The sizeof (count) for the array will always be greater than the number of the highest index. This is due to the fact that indexes start from scratch, of course, but the calculation is that the actual number - and the number of people starts from 1.

You can also use foreach to iterate over an 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 a loop loop condition. This is because PHP calculates a counter for each loop. Assigning a sizeof value to a variable and comparing it is better.

+6
source

How do you solve this ... by studying the scanning of zero-base arrays .

You cannot use $index<=$length as a condition.

Use $index<$length , instead.

 <?php for($d=0;$d<sizeof($datearray);$d++){ ?> ^^^^^ 

And yes, there is a better way:

 <?php foreach($datearray as $date){ ?> <?php echo $date;?> <?php } ?> 

and even better: (PHP endfor / endforeach )

 <?php foreach($datearray as $date): ?> <?php echo $date;?> <?php endforeach; ?> 
+2
source

He must be <. Or use the foreach loop:

 foreach($datearray as $month) { ... } 
+1
source

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, from 0 to 9. The last element in the array should be 1 less than the sizeof array. Thus the for loop should be: for($d=0;$d<sizeof($datearray);$d++)

0
source

Source: https://habr.com/ru/post/1315486/


All Articles