Formatting String With PHP

Introduction

If you want to display a string directly to the browser in its original state then PHP provide two functions that enable you to first apply formatting. So in this article you learn one of the formatting functions, "printf()".

printf() Function

If you are familiar with the C programming language, then you are probably familiar with the printf() function. The printf() function requires a string argument, known as a format control string and it also accepts additional arguments of various types. The format control string contains the instructions for displaying the arguments. Now I am showing an example use of printf() to output an integer as an octal (or base-8) number.

Example

Included within the format control string (the first argument) is a special code, known as a conversion specification. A conversion specification begins with a percent (%) symbol and defines how to treat the corresponding argument to printf(). You can include as many conversion specifications as you want within the format control string, as long as you send an equivalent number of arguments to printf().

<?php
$
no=60;
printf
("The octal number of integer $no is:%o",$no);
?>

Output

octal-number.gif

Type Specifiers of  printf()

You have already seen specifiers (in other words "%o") to display a number as octal, the following table specifies more of the type specifiers:

Specifier Description
b It display an integer as a binary number.
c It display an integer as ASCII equivalent.
d It display argument as a decimal number.
f It display an integer as a floating point number.
o It display an integer as a octal number.
s It display argument as a string.
x It display an integer as a lowercase hexadecimal number (base 16).
X It display an integer as a uppercase hexadecimal number (base 16).

Example

Use the following code in a text file named "all.php". When you access this script through your web browser, it should look something like the following output. As you can see, printf() is a quick way of converting data from one number system to another and outputting the result.

<?php

$number=100;

printf("Binary: %b<br/>",$number);

printf("ASCII: %c<br/>",$number);

printf("Decimal: %d<br/>",$number);

printf("Float: %f<br/>",$number);

printf("Octal: %o<br/>",$number);

printf("Hexaadecimal(lower): %x<br/>",$number);

printf("Hexaadecimal(upper): %x",$number);

?>

Output

all-format.gif 

Although you can use the type specifier to convert from decimal to hexadecimal numbers, you cannot use it to determine how many characters the output for each argument should occupy.

Up Next
    Ebook Download
    View all
    Learn
    View all