Search code examples
phptext

How to echo lines of text vertically in PHP?


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.


Solution

  • 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).