Appending spaces with str_pad

馋奶兔 提交于 2019-12-08 08:01:37

问题


I'm trying to print the contents of an array to the screen, but nicely indented:

function fu($var){
    $lengths = array_map('strlen', array_keys($var));
    $longest = max($lengths);

    echo '<pre>';
    foreach($var as $key => $value){
      echo str_pad($key, $longest - strlen($key)).' =&gt; '.$value."\n";
    }
    echo '</pre>';
}

fu(array(
   'foo'         => 5, 
   'foooooooooo' => 'xxx', 
   'abc'         => 5454545, 
   '1234567890'  => 34, 
   4352354       => 435, 
   'a'           => 'x',
));

For some reason I don't get my output correctly indented.

It should add (max key length) - (key length) spaces. Or isn't my formula correct?


回答1:


str_pad automatically pads to the length specified, you don't need to alter this number based on the length of the string currently being padded.

Therefore, change:

str_pad($key, $longest - strlen($key))

to

str_pad($key, $longest)



回答2:


I'd just use printf's formatting to do this. Use this instead of your echo line:

printf("%-" . $longest . "s =&gt; $value\n", $key, $value);

Or, if you want right-align:

printf("%" . $longest . "s =&gt; $value\n", $key, $value);


来源:https://stackoverflow.com/questions/9280906/appending-spaces-with-str-pad

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!