|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-09-24 00:29 UTC] rick dot foos at solengtech dot com
Description: ------------ 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 to display the square set of values. 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. is_array is a test, not an operation on a null value, and therefore not bad programming requiring a message. http://rickfoosusa.blogspot.com/2011/09/howto-clear-php-undefined-offset.html Test script: --------------- $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 "<tr>"; 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 "<td>"; } } Expected result: ---------------- True or False depending if the array element is valid. Actual result: -------------- True or False depending if the array element is valid. PHP Notice: Undefined offset: 118 in /usr/share/resultsdb/www/index.php on line 465, referer: http://134.86.96.216/resultsdb/index.php? PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 12:00:01 2025 UTC |
>is_array is the correct call to use. What are you blithering about? I think you mean isset(). is_array has nothing to do with it. Anyway, the problem you're having is because you're treating $data_array as a multidimensional array. It's not. PHP has arrays of arrays, not multidimensional arrays (in languages like this you could make a triangular array if you wanted). So if the row is not defined then testing isset on the row's column will complain about the undefined row. So you have to isset on the row to make sure that's there first before you can test its column elements. E.g.: if (isset($data_array[$r + 1]) && isset($data_array[$r + 1][$c + 1])) ... Or like this: for ($r = 0; $r < $row_count; $r++) { echo "<tr>"; if (isset($data_array[$r + 1])) { $row = $data_array[$r + 1]; for ($c = 0; $c < $col_count; $c++) { if (isset($row[$c + 1])) { $data = $row[$c + 1]; } else { $data = null; } echo "<td>", $data; } } else { echo str_repeat("<td>", $col_count); } }