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"
?>//w  ww  . ja  va 2 s  . c om

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!" );
?>//w  w  w .j a  v a  2  s  .  c  om

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"
?>//from w ww .ja v  a 2s . c om

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######"
?>/*  w ww .j  a va  2  s  .  c o  m*/

Result

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

Related Topic