Traversing the matrix and finding ones to calculate their contribution .
for ( $ i = 0 ; $ i < $ R ; $ i ++ ) for ( $ j = 0 ; $ j < $ C ; $ j ++ ) if ( $ mat [ $ i ] [ $ j ] ) $ perimeter += ( 4 - numofneighbour ( $ mat , $ i , $ j ) ) ; return $ perimeter ; }