- array_column: documentation ( source)
- rand: documentation ( source)
<?php
function printTable($matrix)
{
$table = '<table border="1">';
$rows = count($matrix);
for ($i = 0; $i < $rows; $i++)
{
$cols = count($matrix[$i]);
$table .= '<tr>';
for ($j = 0; $j < $cols; $j++)
{
$table .= '<td>' . $matrix[$i][$j] . '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
echo $table;
}
function createMatrix($x, $y)
{
$matrix = [];
for ($i = 0; $i < $x; $i++)
{
$row = [];
for ($j = 0; $j < $y; $j++)
{
$row[] = rand(1, 100);
}
$matrix[] = $row;
}
return $matrix;
}
function transposeArray($array)
{
$i = 0;
$transpose = [];
while ($columns = array_column($array, $i++))
{
$transpose[] = $columns;
}
return $transpose;
}
$table = createMatrix(10, 5);
echo 'Matrix<br/>';
printTable($table);
echo '<br/><br/><br/>';
echo 'Transposed Matrix<br/>';
$table = transposeArray($table);
printTable($table);