function printMatrix(array $matrix): void {
$rows = count($matrix); // number of rows
$cols = count($matrix[0]); // number of columns
for ($i = 0; $i < $rows; $i++) {
$row = '';
for ($j = 0; $j < $cols; $j++) {
// printf with width specifier for padding
$row .= sprintf("%4d", $matrix[$i][$j]);
}
echo $row . PHP_EOL;
}
}
function inverseMatrix(array &$matrix): void {
$rows = count($matrix);
$cols = count($matrix[0]);
$counter = 0;
for ($i = 0, $r = $rows - 1; $i < $rows; $i++, $r--) {
for ($j = 0, $c = $cols - 1; $j < $cols; $j++, $c--) {
// swap values
$temp = $matrix[$i][$j];
$matrix[$i][$j] = $matrix[$r][$c];
$matrix[$r][$c] = $temp;
$counter++;
if ($counter > ($rows * $cols) / 2 - 1) {
return;
}
}
}
}
$matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
echo "matrix:\n";
printMatrix($matrix);
inverseMatrix($matrix);
echo "\ninverse matrix:\n";
printMatrix($matrix);
/*
run:
matrix:
1 2 3 4
5 6 7 8
9 10 11 12
inverse matrix:
12 11 10 9
8 7 6 5
4 3 2 1
*/