Skip to content
Advertisement

Right justifying with 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?

Advertisement

Answer

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}sn", $key, $value);
}

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement