php · level 2 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Three gaps, three values. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$name = "Kai";
$laps = 7;
$time = 12.456;
echo sprintf("%s ran %d laps in %.1f minutes", $name, $laps, $time) . "\n";
your turn
Your turn. Print a till receipt line.
Type an item, its price in pounds, like 1.75, and how many you are buying, as a whole number. Run it.
fix it
Ivy's result will not print. Can you fix it?
- Read the ArgumentCountError: 4 arguments are required, 3 given. The format string counts as one of them.
- Count the gaps in the format string, then count the values after it. One value is missing.
- Add
$gameas the last value, after$score, then press run.
nailed it
your output lines up beautifully. :D
sprintffills each%gap with the next value.%stext,%dwhole numbers,%.2ftwo decimal places.printfechoes the result straight away.
new words in your collection
- sprintf
- format string
- printf
This lesson isn’t saved. A free account remembers every lesson you finish.