The printf() function in PHP allows you to format strings dynamically by replacing placeholders with variable values. It is especially useful for controlling how data (numbers, text, or special formats) appears in the output.
Syntax
int printf(string $format, mixed ...$values);
Parameters:
$format: A string containing placeholders (format specifiers) for formatting output.
$values: Variable values to replace placeholders in the format string.
Return Value:
Returns the length of the outputted string.
Common Format Specifiers
Placeholder
Description
Example Output
%d
Decimal integer
42
%f
Floating-point number
3.14
%s
String
Hello
%x
Hexadecimal (lowercase)
2a
%X
Hexadecimal (uppercase)
2A
%b
Binary representation
101010
%e
Scientific notation
1.23e+4
Basic Example
<?php
$name = "Alice";
$age = 30;
printf("My name is %s, and I am %d years old.", $name, $age);
?>
Output:
My name is Alice, and I am 30 years old.
Formatting Numbers
1. Floating-Point Numbers
<?php
$pi = 3.14159265359;
printf("The value of pi is %.2f", $pi);
?>