Circular Matrix ( Construct a matrix with numbers 1 to m * n in spiral way ) | Fills a [ m ] [ n ] with values from 1 to m * n in spiral fashion . ; Initialize value to be filled in matrix ; k - starting row index m - ending row index l - starting column index n - ending column index ; Print the first row from the remaining rows ; Print the last column from the remaining columns ; Print the last row from the remaining rows ; Print the first column from the remaining columns ; Driver Code
< ? php function spiralFill ( $ m , $ n , & $ a ) { $ val = 1 ; $ k = 0 ; $ l = 0 ; while ( $ k < $ m && $ l < $ n ) { for ( $ i = $ l ; $ i < $ n ; ++ $ i ) $ a [ $ k ] [ $ i ] = $ val ++ ; $ k ++ ; for ( $ i = $ k ; $ i < $ m ; ++ $ i ) $ a [ $ i ] [ $ n - 1 ] = $ val ++ ; $ n -- ; if ( $ k < $ m ) { for ( $ i = $ n - 1 ; $ i >= $ l ; -- $ i ) $ a [ $ m - 1 ] [ $ i ] = $ val ++ ; $ m -- ; } if ( $ l < $ n ) { for ( $ i = $ m - 1 ; $ i >= $ k ; -- $ i ) $ a [ $ i ] [ $ l ] = $ val ++ ; $ l ++ ; } } } $ m = 4 ; $ n = 4 ; spiralFill ( $ m , $ n , $ a ) ; for ( $ i = 0 ; $ i < $ m ; $ i ++ ) { for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { echo ( $ a [ $ i ] [ $ j ] ) ; echo ( " ▁ " ) ; } echo ( " STRNEWLINE " ) ; } ? >