Right justifying with printf

2020-07-13 11:31发布

问题:

I've got a dictionary where both the keys and values are strings. I would like to print each key-value pair on its own line with the key left justified and the value right justified.

Key1        Test
Key2    BlahBlah

Etc...

What's the best way to do this in PHP? Perhaps a clever way to do with printf?

回答1:

Try this:

printf("%-40s", "Test");

The 40 tells printf to pad the string so that it takes 40 characters (this is the padding specifier). The - tells to pad at the right (this is the alignment specifier).

See the conversion specifications documenation.

So, to print the whole array:

$max_key_length = max(array_map('strlen', array_keys($array)));
$max_value_length = max(array_map('strlen', $array));

foreach($array as $key => $value) {
    printf("%-{$max_key_length}s   %{$max_value_length}s\n", $key, $value);
}

Try it here: http://codepad.org/ZVDk52ad



标签: php printf