Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Output and formatting

A program talks to the world through output: the text of a page, a report line, an error message. PHP has several tools for it — from plain echo to templates that align and round values.

echo and print

echo prints one or several values separated by commas:

<?php
 
echo 'Hello', ', ', 'world', "\n";
print "Second line";

print takes a single value only. Otherwise they are equivalent, and echo is used almost always.

Multi-line text

Long text with variables is convenient to write as a heredoc. It starts with <<< and a label name and ends with the same label:

<?php
 
$name = 'Anna';
$total = 1250;
 
echo <<<TEXT
Hello, {$name}!
Order total: \${$total}.
TEXT;

If the label name is put in single quotes, variables are not substituted — the text is printed as is:

<?php
 
echo <<<'TEXT'
The $name variable stays plain text here.
TEXT;

printf templates

printf() puts values into a template in place of markers that start with %:

<?php
 
printf("Product: %s, price: $%d\n", 'Tea', 250);
printf("Discount: %.1f%%\n", 12.5);
printf("Order number: %05d", 42);

The program prints Product: Tea, price: $250, Discount: 12.5% and Order number: 00042.

MarkerMeaning
%sA string
%dAn integer
%fA fractional number
%.2fA fractional number with two decimal places
%05dAn integer padded with zeros to 5 digits
%%A percent sign

sprintf

sprintf() works the same way but returns the string instead of printing it:

<?php
 
$line = sprintf('%s — %.2f', 'Coffee', 399.5);
 
echo $line; // Coffee — 399.50

That is handy when the string must be stored, passed to a function or written to a file.

Numbers

number_format() rounds a number and separates the thousands:

<?php
 
echo number_format(1234567.891, 2), "\n";           // 1,234,567.89
echo number_format(1234567.891, 2, ',', ' '), "\n"; // 1 234 567,89
echo str_pad('7', 3, '0', STR_PAD_LEFT);            // 007

The arguments: the number, decimal places, the decimal separator, the thousands separator.

Debug output

To see what a variable holds, use print_r() and var_dump():

<?php
 
$user = ['name' => 'Anna', 'admin' => true];
 
print_r($user);
var_dump($user['admin']);

print_r() shows the structure of an array, var_dump() also shows value types. echo does not work for an array: it prints the word Array and a warning.

Common mistake

The %d marker drops the fractional part instead of rounding. The price 19.99 turns into 19:

<?php
 
printf("%d\n", 19.99);  // 19
printf("%.2f", 19.99);  // 19.99

For money and other fractional numbers use %.2f or number_format().

Thanks for reading!

Donate to the site — we work hard for you.