I got this problem somewhere, and I want to know how to solve this using PHP. Given this text:
$str = '
PHP is a
widely-used
general-purpose
server side
scripting
language
';
How to echo the text vertically like the given below:
g
e
n
e
w r s
i a e
d l r s
P e - v c l
H l p e r a
P y u r i n
- r p g
i u p s t u
s s o i i a
e s d n g
a d e e g e
I will select the simpler and more elegant code as the answer.
As others have already demonstrated, array_map
is able to do the flip over which is basically the main problem you need to solve. The rest is how you arrange the code. I think your version is very good because it's easy to understand.
If you're looking more to some other extreme, handle with care:
$str = 'PHP is a
widely-used
general-purpose
server side
scripting
language';
$eol = "\n";
$turned = function($str) use ($eol) {
$length = max(
array_map(
'strlen',
$lines = explode($eol, trim($str))
)
);
$each = function($a, $s) use ($length) {
$a[] = str_split(
sprintf("%' {$length}s", $s)
);
return $a;
};
return implode(
$eol,
array_map(
function($v) {
return implode(' ', $v);
},
call_user_func_array(
'array_map',
array_reduce($lines, $each, array(NULL))
)
)
);
};
echo $turned($str), $eol;
Gives you:
g
e
n
e
w r s
i a e
d l r s
P e - v c l
H l p e r a
P y u r i n
- r p g
i u p s t u
s s o i i a
e s d n g
a d e e g e
This fixes the output of the other answer, which was incorrect (now fixed).
The code below will print $str
vertically.
$lines = preg_split("/\r\n/", trim($str));
$nl = count($lines);
$len = max(array_map('strlen', $lines));
foreach ($lines as $k => $line) {
$lines[$k] = str_pad($line, $len, ' ', STR_PAD_LEFT);
}
for ($i = 0; $i < $len; $i++) {
for ($j = 0; $j < $nl; $j++) {
echo $lines[$j][$i].($j == $nl-1 ? "\n" : " ");
}
}
I took some of the code from @bsdnoobz and simplified it. I'm using \n as a line break because I work on a Mac and \r\n doean work here.
$lines = preg_split("/\n/", trim($str));
$len = max(array_map('strlen', $lines));
$rows = array_fill(0,$len,'');
foreach ($lines as $k => $line) {
foreach (str_split(str_pad($line, $len, ' ', STR_PAD_LEFT)) as $row => $char){
$rows[$row] .= $char;
}
}
echo implode("\n",$rows)."\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With