+ 1
I cant understand this code please help me
<?php $matrix = array ( array(2,7,4), array(5,9,8), array(3,0,6) ) ; $n = count($matrix)-1; for($i=0;$i<=$n;$i++) { $temp = $matrix [$i][$i]; $matrix [$i][$i] = $matrix[$i] [$n-$i] ; $matrix [$i][$n-$i] = $temp; } echo $matrix [1][1] . $matrix[0][0]; ?>
2 Réponses
+ 2
From a high level, this program seems to be attempting to reverse arrays. Now for the line-by-line:
$matrix is an array of arrays: AKA a 2d array. $matrix[0] would be [2, 7, 4].
$n = count($matrix) - 1
$matrix has a count of 3, because it contains 3 references to arrays and then 1 is subtracted from it, so $n is 2.
Inside our loop: note that this loop will break if the arrays inside $matrix are not the same size as the number of arrays. i.e. if there are 4 arrays in $matrix, each array inside should also have 4 elements.
$temp = $matrix[$i][$i];
This will set $temp to the diagonal numbers in $matrix as i goes up: 2, 9, 6.
$matrix[$i][$i] = $matrix[$i][$n-$i];
This will set the diagonal numbers to the reverse diagonal numbers as i goes up: 2 = 4, 9 = 9, 6 = 3.
$matrix[$i][$n-$i] = $temp;
This sets the reverse diagonal numbers to the old diagonal numbers as i goes up:
4 = 2, 9 = 9, 3 = 6
Then the center number is concatenated to the top left number and printed:
94
+ 1
Thank you Zeke Williams