← Back to PHP Course | Chapter 6: Strings | Lesson 4 of 8

PHP String Formatting

Basic printf Output

printf() builds a formatted string using placeholders — %s for a string, %d for an integer — and prints the result immediately once every placeholder has been filled in with the corresponding argument's value.

Example: Basic printf Output

php
<?php
printf("Name: %s, Age: %d", "Alice", 30);
?>

Returning Formatted Strings

sprintf() uses the exact same placeholder syntax as printf(), but instead of printing the result right away, it returns the formatted string as a value — letting you store it, pass it to another function, or build it up before deciding whether to output it at all.

Example: Returning Formatted Strings

php
<?php
$formatted = sprintf("Name: %s, Age: %d", "Alice", 30);
echo $formatted;
?>

Formatting Decimals

A format specifier like %.2f controls exactly how many digits appear after the decimal point when formatting a float — %.2f on 3.14159 produces '3.14', rounding to two decimal places rather than truncating or printing the full precision.

Example: Formatting Decimals

php
<?php
printf("%.2f", 3.14159);
?>

Using number_format

number_format() is purpose-built for displaying money and other large numbers: it inserts thousands separators automatically and lets you specify a fixed decimal precision, turning 1234567.891 into a reader-friendly '1,234,567.89' in one call.

Example: Using number_format

php
<?php
echo number_format(1234567.891, 2);
?>

Padding Strings with sprintf

sprintf()'s width specifiers (like %10s) pad a value out to a fixed total width, right- or left-aligning it as needed. That fixed-width alignment is exactly what you need when printing tabular data that has to line up visually in evenly spaced columns.

Example: Padding Strings with sprintf

php
<?php
printf("[%10s]\n", "hi");
printf("[%-10s]", "hi");
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.