×

php · level 2 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

fills a pattern with values, neatly.

sprintf builds a string from a pattern called a . Each gap starts with %. %s takes a string, %d a whole number, and %.2f a number with exactly two decimal places, which suits money. The values follow, in order.

Put a width before the letter to line things up. %-8s pads a string to 8 characters, adding spaces on the right, and %5d pads a number to 5, adding spaces on the left. To show a real percent sign, write %%.

works the same way, but echoes the result straight away.

<?php
$item = "Cocoa";
$price = 2.5;
$label = sprintf("%s costs £%.2f", $item, $price);
echo $label . "\n";
printf("%-8s|%5d|\n", "Pens", 12);
printf("%-8s|%5d|\n", "Rulers", 3);
printf("%d%% off today\n", 20);

%.2f rounds as well, so 2.499 shows as 2.50.