Jump to content

Array help - detect "Undefined offset" ?


benphp

Recommended Posts

I have something that looks like this:

<?php
for ($i=0;$i<=$rowcount;$i++) { 
$sum = $rows[$i];
}
?>

 

But the $rowcount isn't always the same, therefore I get the Undefined offset error. Is there a function that can determine if the offset will be undefined before it attempts the loop? Otherwise, I'll need to write more lines to an already large page.

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/125546-array-help-detect-undefined-offset/
Share on other sites

As kenrbnsn pointed out, you need to use < not <=.  The reason is count() will start counting at 1 but arrays start at 0, so it will never be equal to which is why you get the error.  It is looking for an index 1 greater than the actual size of the array when you have the =.

The issue is a bit more complicated - I simplified it for the question, but here is the actual code. Maybe one of you wizards can figure this one out. The trick is that $colcount may be greater than the elements in the $rows array, because the elements in the $rows array varies:

 

<?php
for ($x=0;$x<=$colcount-1;$x++) {  
print "<td>";
$sum = 0;
for ($i=0;$i<=$rowcount-1;$i++) { //cycle through the row array
	//$rows [row] [column] 
	$sum = $sum + $rows[$i][$x];
	$avg = round($sum / $rowcount, 2);
}
print $avg;
print "</td>";
}
?>

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.