PHP

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

%b

Integer value, binary representation is printed

%c

Integer value, ASCII representation is printed

%d

Integer value, signed decimal value is printed

%e

Decimal value in scientific notation (1.2e+34)

%f

Float value, printed with respect to the locale settings

%F

Float value, printed without respect to the locale settings

%o

Integer value, octal representation is printed

%s

String value

%u

Integer value, unsigned decimal value is printed

%x

Integer value, hexadecimal representation with lowercase letters is printed

%X

Integer value, hexadecimal representation with uppercase letters is printed

The following shows how printf() makes the code a bit easier to read:
<?php
  $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
<?php
  $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
<?php
  $date = '02/01/06';
  $values = sscanf($date, '%d/%d/%d', $m, $d, $y);
  echo "Month: $m; Day: $d; Year: $y.";
?>

by BrainBellupdated
Advertisement: