0
0
PHPprogramming~20 mins

Printf and sprintf formatting in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Printf and sprintf Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code using printf?
Consider the following PHP code snippet. What will it print?
PHP
<?php
$number = 123.456;
printf("%.2f\n", $number);
?>
A123.46
B123
C123.456
D123.45
Attempts:
2 left
💡 Hint
Look at the format specifier %.2f which controls decimal places.
Predict Output
intermediate
2:00remaining
What does this sprintf return?
What string does this PHP code return?
PHP
<?php
$result = sprintf("%05d", 42);
echo $result;
?>
A42
B43
C00042
D41
Attempts:
2 left
💡 Hint
The format %05d pads the number with zeros to width 5.
Predict Output
advanced
2:00remaining
What is the output of this complex printf?
What will this PHP code print?
PHP
<?php
$val = 255;
printf("%#08x\n", $val);
?>
A0x000000ff
B0x0000ff00
C0x0000ff
Dff0000x0
Attempts:
2 left
💡 Hint
The %#08x format prints hex with 0x prefix and pads to 8 characters.
Predict Output
advanced
2:00remaining
What error or output does this code produce?
What happens when this PHP code runs?
PHP
<?php
printf("%d %s", 10);
?>
A10
BWarning: printf(): Too few arguments
C10 %s
D10 0
Attempts:
2 left
💡 Hint
Check if the number of arguments matches the format specifiers.
🧠 Conceptual
expert
2:00remaining
How many characters does this sprintf string have?
What is the length of the string returned by this PHP code?
PHP
<?php
$str = sprintf("%-10s%04d", "Hi", 7);
echo strlen($str);
?>
A13
B12
C10
D14
Attempts:
2 left
💡 Hint
Consider the width specifiers: %-10s and %04d.