PHP - String Format Padding the Output

Introduction

You can add characters to the left (by default) or the right of the formatted argument to pad output to a fixed width.

To add padding you insert a padding specifier into your conversion specification, before the type specifier.

The padding specifier consists of either a zero to pad with zeros or a space character to pad with spaces, followed by the number of characters to pad to.

printf() adds as many zeros or spaces as required to make the result the correct width.

For example, the following code displays various numbers, using leading zeros where necessary to ensure the result is always six digits long:

Demo

<?php

printf("%06d \n ", 123 );   // Displays "000123"
printf("%06d \n ", 4567 );   // Displays "004567"
printf("%06d \n ", 123456 );   // Displays "123456"
?>/* www  .j  av a  2s  . co m*/

Result

The padding specifier can add characters where required, but it never truncates the output.

So printf ("%06d", 12345678 ) displays "12345678", not "345678" .

This example pads various strings using leading spaces to ensure that they're right-aligned:

Demo

<?php
printf("% 15s\n", "Hi" );
printf("% 15s\n", "Hello" );
printf("% 15s\n", "Hello, world!" );
?>/*from  w ww  .  j  a  va2  s.  co m*/

Result

You can also leave out the zero or space and just specify a number, in which case printf() pads with spaces.

You're not limited to zeros and spaces.

To use your own padding character, insert an apostrophe (') followed by the character instead of the zero or space:

Demo

<?php

printf("%'#8s", "Hi" ); // Displays "######Hi"
?>// ww  w . j  a v  a2  s .c  o m

Result

To add padding to the right rather than the left, add a minus (-) symbol between the padding character and the width specifier:

Demo

<?php

printf("%'#-8s", "Hi" ); // Displays "Hi######"
?>//  ww w  .  j a va2 s  . c o  m

Result

Padding behaves differently when using f or F to display a float.

Related Topic