$a = explode(PHP_EOL, trim($str));
$h = max(array_map('strlen', $a));
$w = count($a);
$m = array_map('str_split', array_map('sprintf', array_fill(0, $w, "%{$h}s"), $a));
$t = call_user_func_array('array_map', array_merge(array(null), $m));
echo implode(PHP_EOL, array_map('implode', array_fill(0, $h, ' '), $t)), PHP_EOL;
PHP_EOL should be replaced with "\n", "\r\n" or '<br/>' where appropriate. The whole code after the first line could easily become one big expression, only its readability would suffer a little bit ;-)
$a
is the array of lines, $h
is the final height, $w
is the final width, $m
is the matrix of characters (after padding the strings), $t
is the transposed matrix.
The array_fill(0, $h, ' '),
on the last line can simply be omitted if the space between columns is not needed. On the other hand, not printing trailing space characters can be achieved like this:
echo implode(PHP_EOL, array_map('rtrim', array_map('implode', array_fill(0, $h, ' '), $t))), PHP_EOL;
I have taken the question as an excercise in avoiding explicit loops (which are usually more expensive than loops inside PHP functions, although in this case the advantage could be lost). The important trick here is the matrix transposition, which I have taken from this answer by Codler
Anyhow, the complexity of the whole algorithm is O(width × height)
, just like the one of most algorithms on this page, except for those that repeatedly concatenate strings in order to obtain the lines, whose complexity is O(width² × height)