How to format a string in PHP

Created
Modified

Using sprintf Function

The sprintf() return a formatted string.

sprintf(string $format, mixed ...$values): string

// iPhone 14 Pro
echo sprintf("%s %d Pro\n", "iPhone", 14);

// iPhone 14 Pro
printf("%s %d Pro\n", "iPhone", 14);
iPhone 14 Pro
iPhone 14 Pro

Specifying padding character

// .......14
echo sprintf("%'.9d\n", 14);

// 000000014
echo sprintf("%'.09d\n", 14);

// zero-padded integers
// 01-12
echo sprintf("%02d-%02d", 1, 12);
.......14
000000014
01-12

Formatting Currency

// 14.23
echo sprintf("%01.2f\n", 14.234);

// 14.24
echo sprintf("%01.2f\n", 14.239);
14.23
14.24

Using number_format Function

The number_format() format a number with grouped thousands.

number_format(
    float $num,
    int $decimals = 0,
    ?string $decimal_separator = ".",
    ?string $thousands_separator = ","
): string

$number = 1234.5678;

// 1234.57
echo number_format($number, 2, '.', '');

// 1,234.57
echo number_format($number, 2, '.', ',');

Related Tags