Software Development

PHP Output Formatting

When it comes to creating output that will be returned to a user browser from PHP, there are a number of functions & language constructs available to achieve this. This article will examine the use of echo, print & printf.

Echo

echo allows for simple outputting of 1 or more strings. The following 4 simple examples which produce the same output.

<?php
  echo 'Some Output';
?>
<?php
echo "Some Output";
?>
<?php
$output = "Some Output";
echo $output;
?>
<?php
echo ('Some Output');
?>

Echo is a language construct, not a function, even though it can be used in a function form with brackets as shown above for a single string. Echo cannot be called using variable functions. The following example will NOT work.

($val == 5) ? echo 'true' : echo 'false';

Quoting

The type of quotation marks used in the output of a string, influence the generated output. Strings in double quotations will be evaluated by PHP and so any variables will have their contents substituted for the variable name. Whereas single quotes as treated as literals. The following 2 echo statements will produce different outputs, with the variable substituted in the double quote example, but not in the single quote.

$count = 'Two';
echo "$count more please";
$count = 'Two';
echo '$count more please';

The evaluation within double quotes also allows control or escape sequences, such as n for a linefeed & t for a tab. The full list of escape characters is in the PHP manual.

The display of double quotes within a double quoted string, will require use of the escape character, , the backslash.

<?php
  echo "The man said "it is true" to the reporter.";
?>

The same is true for use of the single quote within a single quoted string.

<?php
  echo 'The order doesn't matter.';
?>

Concatenation

Echo handles multiple string concatenation (with the period operator), or multiple strings passed as parameters, either as literal strings or variables. So the following produce the same output.

$dayPart = 'morning';
echo 'A good ' . $dayPart . '.';
$dayPart = 'morning';
echo 'A good ' , $dayPart , '.';

Short Cut

There is a short cut syntax for echo, with an equals immediately after the short opening tag.

<?= $variable ?>

Use of this syntax requires that the short open tag <? is controlled in the PHP configuration. For maximum compatibility across systems, it is best to not use this format, as many web servers will have it turned off.

Print

Print works much the same as echo. Again it is a language construct not a function, but unlike echo, print does have a return value (true or false).

<?php
  print 'Some print output';
?>

The same quoting rules as outlined above apply for print on strings.

<?php
  $count = 'Two';
  print "$count more please";
?>

Multiple string concatenation (with the period operator) works with print, but multiple strings passed as parameters does not.

Printf

printf outputs a string, according to a supplied format. It allows for some very fine grained output control, and is suited to more complex output creation. The same results can be achieved by use of print or echo, but printf can allow the creation of more succinct and/or maintainable code. printf has the following signature:

printf (string format [, mixed args...])

where format is a string that has the basic outline with conversion specifications instead of variables, followed by parameters that will be substituted into the format string. The return value is the length of the outputted string. A simple example:

<?php
  $count = 3;
  $cost = 25.2;
  $format = "The %d items cost $%.2f.";
  printf($format, $count, $cost);
?>

The advantages of printf become more obvious as the number and complexity of substitutions increase.

<?php
foreach ($orderList as $order) {
  printf("Customer %s ordered %d items, with a total cost of $%.2f including $%.2f tax.",
	$order['first_name'].' '.$order['surname'],
	$order['count'],
	$order['cost'] * ($order['tax_rate'] + 1),
	$order['cost'] * $order['tax_rate']
  )
}
?>

The format for each conversion specification is: %[-|+][padding character][-][width][.precision]type. Only the leading % and the type specification is mandatory, with the output types as:

b Argument is treated as an integer, and presented as a binary number.
c Argument is treated as an integer, and presented as the character with that ASCII value.
d Argument is treated as an integer, and presented as a (signed) decimal number.
e Argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less)
E Like %e but uses uppercase letter (e.g. 1.2E+2).
u Argument is treated as an integer, and presented as an unsigned decimal number.
f Argument is treated as a float, and presented as a floating-point number (locale aware).
F Argument is treated as a float, and presented as a floating-point number (non-locale aware).
g Shorter of %e and %f.
G Shorter of %E and %f.
o Argument is treated as an integer, and presented as an octal number.
s Argument is treated as and presented as a string.
x Argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X Argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Above modified from PHP manual list of specifiers

The optional elements are:

  1. sign specifier (- or +)
  2. padding specifier to the right size string. The default is space.
  3. alignment specifier. - will make it left justified, with a default of right justified.
  4. width specifier. Minimum number of characters.
  5. precision specifier. Period (.) followed by a number that specifies how many digits to be displayed for floating point numbers, or a maximum character limit when applied to a string.

To display an actual % sign, use %% in the format string.

Argument Ordering and reuse

Placeholder substitution need not be done in parameter order, and supplied parameters can be substituted more than once, as shown below:

<?php
  printf('%2$s played against %1$s and the winner was %1$s', 'Spain', 'Netherlands');
?>
<?php
  printf('%1$s as a string, %1$.2f as a floating point, %1$d as a decimal number, %1$o as octal, and %1$x in hexadecimal.', 123.653);
?>
Standard