Sometimes is programming line you may need diagonal values of a 2D array. Today in this article I will help you how you can get 2D array’s diagonal values in PHP programming language. Before the start, we should know the logic behind the function. Let suppose we have an array i.e.
1 2 3
4 5 6
7 8 9
Here, diagonal values will be. ar1 = 1,5,9 and ar2 = 3,5,7. We should check that array must be a square. If the input array is not a square we should throw an exception because error handling is the best practice.
Here is the code that will fetch diagonal values from a 2D array in PHP.