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.

JavaScript

Etc…

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

Advertisement

Answer

Try this:

JavaScript

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:

JavaScript

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

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