0

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

    }
4
  • Clearly, you should compare the array only up to the next-to-last element, and no further. Your first example explicitly checks that $row is not zero, so $row-1 always exists. Commented May 27, 2020 at 14:50
  • can you show your complete for-loop? Commented May 27, 2020 at 15:19
  • As a quick fix, you can use the null coalesce operator ?? - $items[$row+1][0] ?? -1 (the -1 would be some dummy value which you can set to something appropriate for your case). Commented May 27, 2020 at 15:38
  • @NigelRen That's good to know. Thank you. Commented May 27, 2020 at 15:43

1 Answer 1

1

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>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I didn't know that empty can check the index. It worked. Can't believe I struggled for a couple of days for this...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.