Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

printf()

Synopsis

    int printf ( string format [, mixed argument [, mixed ...]] )

The printf() function may not be a function you will use often, but many people do, so it is good for you to be aware of it. This function is the standard C way to format text, and it has 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.

This function takes a variable number of parameters: a format string is always the first parameter, followed by zero or other parameters of various types. Here is a basic example:

    $animals = "lions, tigers, and bears";
    printf("There were %s - oh my!", $animals);

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

Here is another example, slightly more complicated this time:

    $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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page