Skip to content

Instantly share code, notes, and snippets.

@falmp
Last active August 29, 2015 13:57
Show Gist options
  • Save falmp/9625261 to your computer and use it in GitHub Desktop.
Save falmp/9625261 to your computer and use it in GitHub Desktop.
Pretty print a matrix (bidimensional array)
<?php
/**
* Pretty print a matrix (bidimensional array).
*
* @author Francisco Lopes <chico.lopes@gmail.com>
* @param array $matrix The matrix to print
* @return void
*/
function print_matrix(array $matrix) {
if (!count($matrix) || !count($matrix[0]))
return;
$width = max(array_map('strlen', call_user_func_array('array_merge', $matrix)));
$column = str_repeat('─', $width);
echo '┌' . str_repeat($column . '┬', count($matrix[0]) - 1) . $column . '┐' . PHP_EOL;
for ($i = 0; $i < count($matrix); $i++) {
echo '│';
for ($j = 0; $j < count($matrix[$i]); $j++) {
echo str_pad($matrix[$i][$j], $width, ' ', STR_PAD_LEFT) . '│';
}
echo PHP_EOL;
if ($i < count($matrix) - 1)
echo '├' . str_repeat($column . '┼', count($matrix[$i]) - 1) . $column . '┤' . PHP_EOL;
}
echo '└' . str_repeat($column . '┴', count($matrix[0]) - 1) . $column . '┘' . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment