🎓 A1Learner
🔍
0 of 38 lessons completed

Formatting Text

Formatting functions build text to an exact shape instead of printing raw values. A built string can carry labels, grouped digits, and columns that line up.

sprintf builds a labelled line

The pattern holds two placeholders here. The %s mark takes the word Book and the %d mark takes the number 12.

<?php
$line = sprintf("%s costs %d dollars", "Book", 12);
echo $line . "\n";

number_format groups the digits

The raw float prints first with no grouping. number_format then writes the same value with commas and exactly two decimal places.

<?php
$price = 1234567.891;
echo $price . "\n";
echo number_format($price, 2) . "\n";

str_pad lines up two names

Both names pad to a width of 8 with dots. The scores then start in the same column on both lines.

<?php
echo str_pad("Ana", 8, ".") . "8\n";
echo str_pad("Ben", 8, ".") . "9\n";

Example

<?php
$pen = sprintf("%s %s dollars", str_pad("Pen", 8, "."), number_format(5.5, 2));
$book = sprintf("%s %s dollars", str_pad("Book", 8, "."), number_format(12, 2));
echo $pen . "\n";
echo $book . "\n";

Key points

  • sprintf builds a string from a pattern and a set of values.
  • A placeholder is a mark in the pattern that a value fills, like %s for text and %d for a whole number.
  • sprintf hands the built string back, so the program chooses when to print it.
  • number_format writes a number as text with commas between groups of digits.
  • The second value given to number_format sets how many decimal places the text shows.
  • str_pad lengthens a string to a set width by adding characters on one side.

In this example, two price tag lines are built with the three formatting functions together. str_pad widens each name to 8 characters with dots, so the prices start in the same column. number_format writes each price with two decimal places. sprintf places the padded name and the price into one line each, and the two lines print as a small aligned block.

Note

number_format hands back text, so a formatted price is ready to print and not to add.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does number_format(1234.5, 2) hand back?