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 characters
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 |
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.