Printf and sprintf help you create text with numbers or words in a neat, controlled way.
Printf and sprintf formatting in PHP
Introduction
Syntax
PHP
printf(format, arg1, arg2, ...); sprintf(format, arg1, arg2, ...);
printf prints the formatted string directly.
sprintf returns the formatted string without printing it.
Examples
PHP
printf("Hello %s!", "Alice");
PHP
$price = 12.5; printf("Price: $%.2f", $price);
PHP
$text = sprintf("Number: %04d", 7);
Sample Program
This program shows how to use printf to print formatted text and sprintf to create a formatted string.
PHP
<?php $name = "Bob"; $age = 30; $score = 95.6789; // Print a greeting printf("Hello %s!\n", $name); // Print age with label printf("Age: %d years\n", $age); // Print score with 2 decimals printf("Score: %.2f\n", $score); // Create a formatted string with sprintf $info = sprintf("Name: %s, Age: %d, Score: %.1f", $name, $age, $score); echo $info . "\n"; ?>
Important Notes
Use %s for strings, %d for integers, and %f for floating-point numbers.
You can control decimal places with %.2f (2 decimals) or %.1f (1 decimal).
Remember printf prints immediately, sprintf returns the string for later use.
Summary
Printf and sprintf format text by inserting variables in a controlled way.
Printf prints the result; sprintf returns it as a string.
Use format codes like %s, %d, and %f to specify how variables appear.
Practice
1. What does the
%s format specifier do in printf or sprintf in PHP?easy
Solution
Step 1: Understand format specifiers
The%sspecifier is used to insert a string value into the formatted output.Step 2: Match specifier to variable type
Since%sis for strings, it converts the variable to a string representation.Final Answer:
It formats the variable as a string. -> Option AQuick Check:
%s = string [OK]
Hint: Remember %s means string, %d integer, %f float [OK]
Common Mistakes:
- Confusing %s with %d or %f
- Using %s for numbers without converting
- Thinking %s formats booleans
2. Which of the following is the correct syntax to print a floating-point number with 2 decimal places using
printf in PHP?easy
Solution
Step 1: Identify correct decimal precision syntax
In PHP, to format a float with 2 decimals, use%.2fwhere .2 specifies 2 decimal places.Step 2: Check each option's format string
Only printf("%.2f", $number); uses%.2fcorrectly; others have misplaced or incorrect syntax.Final Answer:
printf("%.2f", $number); -> Option AQuick Check:
%.2f = float with 2 decimals [OK]
Hint: Use %.Nf to print float with N decimals [OK]
Common Mistakes:
- Placing decimal after %f instead of before
- Using %2f instead of %.2f
- Adding extra characters inside format string
3. What will be the output of the following PHP code?
$name = "Alice";
$score = 95.678;
printf("Student: %s, Score: %.1f", $name, $score);
medium
Solution
Step 1: Analyze format specifiers
%s inserts the string$nameas is. %.1f formats$scoreas a float with 1 decimal place, rounding the value.Step 2: Calculate rounded float
95.678 rounded to 1 decimal place is 95.7.Final Answer:
Student: Alice, Score: 95.7 -> Option BQuick Check:
%.1f rounds 95.678 to 95.7 [OK]
Hint: %.1f rounds float to 1 decimal place [OK]
Common Mistakes:
- Not rounding float correctly
- Confusing %s and %f usage
- Expecting full float without formatting
4. Identify the error in this PHP code snippet:
$value = 123;
printf("Value is %d.2", $value);
medium
Solution
Step 1: Check format specifier syntax
%d is for integers and does not support precision like .2. The correct usage is just %d.Step 2: Understand error cause
Adding .2 after %d causes invalid format syntax, leading to an error or unexpected output.Final Answer:
The format specifier %d.2 is invalid syntax. -> Option CQuick Check:
%d does not take precision like %.2f [OK]
Hint: Use %d alone for integers; no decimal precision [OK]
Common Mistakes:
- Trying to add decimal precision to %d
- Confusing %d and %f format specifiers
- Assuming printf auto-corrects invalid formats
5. You want to create a formatted string showing a product's name left-aligned in 10 spaces and its price right-aligned in 8 spaces with 2 decimals. Which
sprintf format string is correct?$product = "Pen";
$price = 1.5;
$result = sprintf("...", $product, $price);
hard
Solution
Step 1: Understand alignment and width specifiers
%-10s means left-align string in 10 spaces. %8.2f means right-align float in 8 spaces with 2 decimals.Step 2: Match requirements to options
"%-10s%8.2f" matches left-aligned product name in 10 spaces and right-aligned price with 2 decimals in 8 spaces.Final Answer:
"%-10s%8.2f" -> Option DQuick Check:
%-10s left-align string, %8.2f right-align float [OK]
Hint: Use - for left-align, number for width, .N for decimals [OK]
Common Mistakes:
- Mixing alignment flags (-) with wrong specifier
- Swapping width numbers for string and float
- Forgetting .2 for decimal precision on float
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
