sprintf() returns a formatted string without printing it. Use placeholders that match the data type you want to format.
$name = 'Ravi';
$score = 92;
$message = sprintf('%s scored %d', $name, $score);
echo $message;
string sprintf ( string $format [, mixed $values ] )
$format: A string specifying how to format the values.$name = "John";
$score = 90;
echo sprintf("Student %s scored %d points", $name, $score);
Output:
Student John scored 90 points
$price = 123.456;
echo sprintf("The price is %.2f", $price);
Output:
The price is 123.46
$order = 42;
echo sprintf("Order number: %05d", $order);
Output:
Order number: 00042
$text = "This is a long string";
echo sprintf("%.10s", $text); // Truncate to 10 bytes
Output:
This is a
$age = 25;
$height = 5.8;
echo sprintf("Age: %d, Height: %.1f feet", $age, $height);
Output:
Age: 25, Height: 5.8 feet
$number = 255;
echo sprintf("Hex: %X, Octal: %o", $number, $number);
Output:
Hex: FF, Octal: 377
| Specifier | Description |
|---|---|
| %s | String |
| %d | Integer (signed decimal number) |
| %f | Floating-point number |
| %.2f | Floating-point number with 2 decimal places |
| %05d | Padded integer with leading zeros (5 digits) |
| %x | Hexadecimal number (lowercase) |
| %X | Hexadecimal number (uppercase) |
| %o | Octal number |
| %c | Character corresponding to an ASCII value |
| %% | A literal percent sign |
htmlspecialchars(); formatting is not HTML escaping.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.