Printing Strings, Variables, and Expressions Simultaneously

Using double quotation marks, printing a mixture of strings and variables is easy to do. However, when you also want to use expressions such as function calls, the standard way is to use lots of string concatenations:
echo 'The length of the string is ' . strlen($s) .
This is obviously getting rather complex when several expressions are involved.
A more convenient way is to use printf(). As parameters, you provide first a string with placeholders, and then the values for those placeholders. Table shows which values are allowed for a placeholder.

Placeholders for printf() and Related Functions

Placeholder Description


Integer value, binary representation is printed


Integer value, ASCII representation is printed


Integer value, signed decimal value is printed


Decimal value in scientific notation (1.2e+34)


Float value, printed with respect to the locale settings


Float value, printed without respect to the locale settings


Integer value, octal representation is printed


String value


Integer value, unsigned decimal value is printed


Integer value, hexadecimal representation with lowercase letters is printed


Integer value, hexadecimal representation with uppercase letters is printed

The following shows how printf() makes the code a bit easier to read:
  $a = 'PHP';
  $b = 'php';
  printf('strcmp(): %d<br />strcasecmp(): %d',
    strcmp($a, $b), strcasecmp($a, $b));
PHP also supports several functions related to printf():
  • sprintf() works like printf(), but returns the string and does not print it.

  • vprintf() works like printf(), however expects the values for the placeholders in the string to be in the form of an array.

  • vsprintf() is a mixture of sprintf() and vprintf(): The placeholder values are provided in an array and the function returns the string but does not print it.

Scanning Formatted Strings

sscanf($date, '%d/%d/%d')

Another function related to printf() is sscanf(). This one parses a string and tries to match it with a pattern that contains placeholders. The $input string contains a date and is scanned using the string '%d-%d-%d' with several placeholders, as shown in the previous coding. The function returns an array with all values for the matched placeholders. Then this array is passed to vprintf() to print it.

Scanning Formatted Strings
  $date = '02/01/06';
  $values = sscanf($date, '%d/%d/%d');
  vprintf('Month: %d; Day: %d; Year: %d.', $values);

Alternatively, you can provide a list of variable names as additional parameters to sscanf(). Then the function writes the substrings that match the placeholders into these variables. The following code shows this:

Scanning Formatted Strings
  $date = '02/01/06';
  $values = sscanf($date, '%d/%d/%d', $m, $d, $y);
  echo "Month: $m; Day: $d; Year: $y.";