Reputation: 43
I have 2D arrays where I have to keep comparing the next value.
I am using a for loop to go through all values and I am getting an offset error because when it reaches the last array, it wants to check the next array, which does not exist. How can I prevent that? I know that ($items[$row][0]!=$items[$row+1][0]) is the issue. Should I not use a for loop?
What I do not understand is that the code below does not give any error. If $items[$row+1][0] is the problem when it reaches the last array, shouldn't $items[$row-1][0] give an error as well when it is checking the first array in the arrays?
if ($row==0 || ($row>0 && $items[$row][0]!=$items[$row-1][0]) )
But this one is not ok.
Notice: Trying to access array offset on value of type null
Notice: Undefined offset
if (($row<$num_rows && ($items[$row][0]!=$items[$row+1][0]))||$num_rows==$is_odd) {
//$is_odd is the number of last array.
//$num_rows is the total number of arrays.
echo "</table></div></div>";
}
Upvotes: 0
Views: 74
Reputation: 827
in your condition check next index is exist or not like
if ((!empty($items[$row + 1]) && $row < $num_rows && ($items[$row][0] != $items[$row + 1][0])) || $num_rows == $is_odd) {
//$is_odd is the number of last array.
//$num_rows is the total number of arrays.
echo "</table></div></div>";
}
Upvotes: 1