undefined offset notice when looping through arrays in php - Stack Overflow
PHP Notice: Undefined offset: 118 in /usr/share/resultsdb/www/index.php on line 465, referer: ...
While this seems to simple to write about, there weren't any posts with the answer. Even one specifically about sparse matrices didn't answer the question.
There is also bug in PHP is_array() which started this journey in the first place.
https://bugs.php.net/bug.php?id=55772
There are several HowTo's on 'PHP Notice Undefined offset' from webmasters wondering what is filling their logs, to lectures on bad programming.No one answers the question.
I have a sparse matrix, that needs each element to display on an html page. So when the matrix is loaded with defined values there are many undefined values, 6158 for example.
This is displayed as a square matrix using an HTML table - A conflict between good PHP programming and HTML programming. The undefined elements need some html, so the 'for loops' must touch each element of the array.
is_array is the correct call to use. It tests array elements, and returns true or false if they are valid or not.
While the is_array function returns true and false - PHP still issues the warning message.
For now, the isset function can be used. It's not obvious that is applies to arrays, but it works.
$data_array=array();
$data_array[2][10] = "defined";
$row_count = 10;
$col_count = 10;
//...fill with the defined values...many values undefined.
for ($r = 0; $r < $row_count; $r++)
{
echo "";
for ($c = 0; $c < $col_count; $c++)
{
if (
isset($data_array[$r+1][$c+1])){
$data = $data_array[$r+1][$c+1];
} else {
$data = NULL;
}
echo "";
}
}