Formatting with sprintf in PHP
printf-style templates for columns, padding and number bases.
<?php
$item = "espresso";
$price = 3.5;
$qty = 12;
echo sprintf("%-12s $%5.2f\n", $item, $price);
printf("%08.3f\n", 3.14159);
printf("hex %x, octal %o, binary %b\n", 255, 255, 255);
printf("%'.10s x%03d\n", "total", $qty);
$row = sprintf("| %-8s | %6.2f |", $item, $price * $qty);
echo $row, "\n";
How it works
%-12sleft-aligns a name;%5.2fright-aligns a price to two decimals.%08.3fzero-pads;%x,%oand%bprint one value in three bases.sprintfreturns the string instead of printing — handy for building rows.
Keywords and builtins used here
echoprintfsprintf
The run, in numbers
- Lines
- 12
- Characters to type
- 300
- Tokens
- 85
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 73 seconds.
Step 2 of 3 in Strings & regex, step 14 of 27 in Language basics.