PHP Error Notice: Undefined offset:

This error comes when we use a loop to read array elements and run loop to read an array memory location which is empty or Null.

For example next program will show error Notice: Undefined offset:
 $people = array("Peter", "Joe", "Glenn", "Cleveland");
 for($i = 0; $i <= count($people); $i++)
 {
 echo "$people[$i]";
 }
 
There are four elements in the array. It show error because we run five time so this gives error.
To correct this program we use only '<'
 for($i = 0; $i < count($people); $i++)
 {
 echo "$people[$i]";
 }
 
Conclusion
First program start from 0th element and run loop to 5th element but there is 5th place is empty. As we use '<=' so it gives error 'Notice: Undefined offset: 4'

Second program start from 0th element and run loop to 4th element.

Now see this loop.
 for($i = 0; $i <= 6; $i++)
 {
 echo "$people[$i]";
 }
 
This loop in program shows element of array and produce three time this error message
 Notice:Undefined offset: 4 in D:\tester\ar1.php on line 103

Notice: Undefined offset: 5 in D:\tester\ar1.php on line 103

Notice: Undefined offset: 6 in D:\tester\ar1.php on line 103
 

this notice show three time because there are only four element in array. But we are try to show 0 to 6 ( Seven element) elements.

So this error notice produced when we try to show a array location which is not assigned a value.
Valid CSS!

Online Business Solutions

Share |