Correct alignment with printf

I have a dictionary where both keys and values ​​are strings. I would like to print each key-value pair in its own line with a confirmed key and justification for the value.

Key1 Test Key2 BlahBlah 

Etc ...

What is the best way to do this in PHP? Perhaps a smart way to do it with printf?

+4
source share
1 answer

Try the following:

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

40 tells printf to fill in the string so that it occupies 40 characters (this is a pad specifier). - indicates the right button (this is the alignment specifier).

See documentation for conversion specifications .

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

+8
source

All Articles