typestar

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

  1. %-12s left-aligns a name; %5.2f right-aligns a price to two decimals.
  2. %08.3f zero-pads; %x, %o and %b print one value in three bases.
  3. sprintf returns the string instead of printing — handy for building rows.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Strings & regex, step 14 of 27 in Language basics.

← Previous Next →

Formatting with sprintf in other languages