Created
August 10, 2018 05:17
-
-
Save tanmay27vats/7116a0b20363e34056589dfc08894902 to your computer and use it in GitHub Desktop.
Get 2D array's diagonal values in PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function diagonalValues($arr) { | |
$d_ar = []; | |
$main_len = count($arr); | |
foreach($arr as $key => $ar) { | |
$sub_len = count($ar); | |
if($main_len != $sub_len) { | |
throw new Exception('Array index count mismatched. Hence this is not square array.'); | |
} | |
$d_ar[0][] = $ar[$key]; | |
$d_ar[1][] = $ar[($main_len-$key-1)]; | |
} | |
return $d_ar; | |
} | |
$arr = [ | |
[1,2,3], | |
[4,5,6], | |
[9,8,9] | |
]; | |
$result = diagonalValues($arr); | |
print_r($result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment