Hudzilla.org - the homepage of Paul Hudson
Contents > Functions > Playing with strings Wish List | Report Bug | About Me ]

4.7.17     Complex string printing: printf()

This is NOT the latest copy of this book; click here for the latest version.

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

Printf() may well not be a function you will use too often, but many people do, so it is good for you to know. Printf() is the C and C++ way to format text, and it is been copied wholesale into PHP for those who want to make use of it. It is not easy to use, but if you are doing a lot of code formatting it will produce shorter code.

Printf() takes a variable number of parameters - a format string is always the first parameter, followed by zero or more other parameters of various types. Here is a basic example:

<?php
    $foo
= "lions, tigers, and bears";
    
printf("There were %s - oh my!", $foo);
?>

That will put together the string "There were lions, tigers, and bears - oh my!" and send it to output. %s is a special format string that means "string parameter to follow", which means that $foo will be treated as text inside the string that printf() creates.

Here is another example, slightly more complicated this time:

<?php
    $foo
= "you";
    
$bar = "the";
    
$baz = "string";

    
printf("Once %s've read and understood %s previous section, %s should be able to use %s bare minimum %s control functions to help %s make useful scripts.", $foo, $bar, $foo, $bar, $baz, $foo);
?>

This time we have several %s formatters in there, and the corresponding number of variables after parameter one. PHP replaces the first %s with parameter two, the second %s with parameter three, the third %s with parameter four, and so on. Note that we have both $foo and $bar appearing more than once in the format list, which is perfectly acceptable.

Printf() takes a variety of other format strings as well as %s. Here is the complete list:

Format

Meaning

%%

A literal percent character; no matching parameter is required

%b

Parameter is an integer; present it as binary

%c

Parameter is an integer; present it as a character with that ASCII value

%d

Parameter is an integer; present it as a signed number

%f

Parameter is a float; present it as a float

%o

Parameter is an integer; present it as octal

%s

Parameter is a string; present it as a string

%x

Parameter is an integer; present it as hexadecimal with lowercase letters

%X

parameter is an integer; present it is hexadecimal with uppercase letters

A few of those may well not make sense at first, so an example is called for. One quick note, first, though: if, for example, you use %s then pass a number in the corresponding parameter, PHP will treat the number as a string. The same goes for all parameters - if you specify one type then pass in another in its place, PHP will treat it as the type you specified it was, not as the type it actually is. This is a good thing, because you cannot always be sure what type a variable is, yet you can always be sure what kind of variable you would like it to be.

<?php
    $number
= 123;
    
printf("123 in binary is: %b", $number);
    
printf("123 in hex is: %h", $number);
    
printf("123 as a string is: %s", $number);
    
printf("%% allows you to print percent characters");
?>

If you are thinking that printf() might not sound useful, you perhaps have not yet grasped quite how much it can do for you. Consider, for example, that you can now put the strings for parameter one separate from the printf() call, which means you can change languages at the drop of a hat.

Furthermore, it means you do not need to add new variables to your script to perform conversions - printf() will do them all for you, particularly thanks to an extra piece of functionality it has, revolving around the use of . (a full stop). Take this piece of code as an example:

<?php
    $number
= 123.456;
    
$formatted = number_format($number, 2) . "\n";
    print
"Formatted number is $formatted\n";
    
printf("Formatted number is %.2f\n", $number);
?>

In that code lines two and three handle rounding our float to two decimal places then printing out the result. However, the same thing is accomplished in line three - %f is the format term meaning "float", but by preceding the F with .2 (that is a full stop followed by a two) we're instructing printf() to round the float to two decimal places. We could have used .1 for one decimal place, .8 for eight decimal places, etc. So, as you can see, printf() can make your code a great deal easier to read, as well as allowing you to keep your text separate from your variables!





<< 4.7.16 Padding out a string: str_pad()   4.7.18 Parsing a string into variables: parse_str() >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
deathgod - 30 Aug 2008

one of the best ways to personalise your website with user information is using printf() in conjunction with databases. Like for example displaying a greeting message. I came across the following example while using osCommerce(open-source eCommerce solution):
I have simplified it alot for you to understand


$customer_first_name = mysql_query(select * first_name); //this varible is assigned to the database record first_name(for example: deathgod, so in this case $customer_first_name = deathgod)

$greetingstring = printf(Welcome back %s enjoy your shopping experience, $customer_first_name);

echo $greetingstring

This will print:
Welcome back deathgod enjoy your shopping experience

excellent function, right? hope you have understood what i said and find it useful

deathgod - 30 Aug 2008

one of the best ways to personalise your website with user information is using printf() in conjunction with databases. Like for example displaying a greeting message. I came across the following example while using osCommerce(open-source eCommerce solution):
I have simplified it alot for you to understand


$customer_first_name = mysql_query(select * first_name); //this varible is assigned to the database record first_name(for example: deathgod, so in this case $customer_first_name = deathgod)

$greetingstring = printf(Welcome back %s enjoy your shopping experience, $customer_first_name);

echo $greetingstring

This will print:
Welcome back deathgod enjoy your shopping experience

Steve - 30 Aug 2008

School kid, you should be more specific, don't you think? People here are helpful if you ask the right question.

A PHP User - 30 Aug 2008

please write in english that school kids doing their homework can understand!

ewauters@androme.com - 30 Aug 2008

The example below the format specficiers table has the %h to print the hexadecimal value to the output. This should be either %x or %X.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is six plus seven?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow