Blanktext
Blanktext

Reputation: 1538

How do alignment specifiers and width specifiers work with printf() and sprintf() in PHP?

I am studying about printf and sprintf and I don't understand a few points. Can someone please help me understand the following format specifiers explained at sprintf():

Upvotes: 2

Views: 675

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

Let's take a simple example:

<?php

$strs = "hello world";
printf("%-15s", $strs);
echo "\n";
printf("%15s", $strs);

?>

output:

hello world    
    hello world

^^^^^^^^^^^^^^^
|||||||||||||||
123456789012345  (width=15)

Here 15 is the minimum printed width of the string, and the - sign is to indent the string on the left.

Upvotes: 2

Marc B
Marc B

Reputation: 360602

width specifier:

given:    printf('|%5d|', 1);
prints:   |    1|
           ^^^^^-- 4 spaces + 1 char = width of 5

alignment:

given:    printf('|%-5d|', 1);
prints    |1    |
           ^^^^^-- 1 char + 4 right-justified spaces = width of 5.

Upvotes: 7

Related Questions