Skip to content

Instantly share code, notes, and snippets.

@tanmay27vats
Created August 10, 2018 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanmay27vats/7116a0b20363e34056589dfc08894902 to your computer and use it in GitHub Desktop.
Save tanmay27vats/7116a0b20363e34056589dfc08894902 to your computer and use it in GitHub Desktop.
Get 2D array's diagonal values in PHP.
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