Jump to content

Array help - detect "Undefined offset" ?


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

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.