0
0
PHPprogramming~10 mins

Printf and sprintf formatting in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Printf and sprintf formatting
Start
Prepare format string
Provide values to format
Call printf or sprintf
printf: Output formatted string directly
sprintf: Return formatted string
End
The program prepares a format string and values, then calls printf or sprintf to format the string. printf prints it directly, sprintf returns it.
Execution Sample
PHP
<?php
$number = 42;
printf("Number: %d\n", $number);
$str = sprintf("Hex: %x", $number);
echo $str;
?>
This code prints a decimal number using printf and stores a hex string using sprintf, then prints it.
Execution Table
StepActionFormat StringValueResult/Output
1Set $number-42-
2Call printfNumber: %d\n42Number: 42 (printed)
3Call sprintfHex: %x42Hex: 2a (returned)
4echo $str--Hex: 2a (printed)
5End--Execution stops
💡 All statements executed, program ends.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
$numberundefined424242
$strundefinedundefinedHex: 2aHex: 2a
Key Moments - 3 Insights
Why does printf print directly but sprintf does not?
printf outputs the formatted string immediately (see step 2 in execution_table), while sprintf returns the formatted string for later use (see step 3).
What does %d and %x mean in the format string?
%d formats the value as a decimal integer (step 2), %x formats it as a lowercase hexadecimal (step 3).
Why do we need to echo $str after sprintf?
sprintf returns the formatted string but does not print it, so echo is needed to display it (step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed by printf at step 2?
A42
BHex: 2a
CNumber: 42
DHex: 42
💡 Hint
Check the 'Result/Output' column at step 2 in execution_table.
At which step does $str get its value?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at variable_tracker for $str changes and execution_table step 3.
If we change %x to %X in sprintf, what changes in output?
AOutput becomes uppercase hex letters
BOutput becomes decimal number
COutput becomes binary number
DNo change in output
💡 Hint
Recall %x is lowercase hex, %X is uppercase hex formatting.
Concept Snapshot
printf and sprintf format strings with placeholders like %d, %x.
printf prints formatted string directly.
sprintf returns formatted string for later use.
Use echo to print sprintf result.
Placeholders control how values appear.
Full Transcript
This example shows how printf and sprintf work in PHP. First, a number 42 is stored in $number. Then printf prints 'Number: 42' using %d to format the number as decimal. Next, sprintf formats the number as hexadecimal with %x and returns the string 'Hex: 2a' which is stored in $str. Finally, echo prints the $str value. printf outputs immediately, sprintf returns a string. Placeholders like %d and %x control formatting style.