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

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.