Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right justifying with printf

Tags:

php

printf

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?

like image 368
Jonathan Avatar asked Sep 11 '11 20:09

Jonathan


1 Answers

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

like image 124
Arnaud Le Blanc Avatar answered Sep 18 '22 12:09

Arnaud Le Blanc