13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Formatting Strings<br />

111<br />

Figure 4.2<br />

Using <strong>PHP</strong>’s nl2br() function improves the display<br />

of long strings within HTML.<br />

Both of these techniques print a string “as is.”You can apply some more sophisticated<br />

formatting using the functions printf() <strong>and</strong> sprintf().They work basically the same<br />

way, except that printf() prints a formatted string to the browser <strong>and</strong> sprintf()<br />

returns a formatted string.<br />

If you have previously programmed in C, you will find that these functions are conceptually<br />

similar to the C versions. Be careful, though, because the syntax is not exactly<br />

the same. If you haven’t, they take getting used to but are useful <strong>and</strong> powerful.<br />

The prototypes for these functions are<br />

string sprintf (string format [, mixed args...])<br />

void printf (string format [, mixed args...])<br />

The first parameter passed to both of these functions is a format string that describes the<br />

basic shape of the output with format codes instead of variables.The other parameters<br />

are variables that will be substituted in to the format string.<br />

For example, using echo, you can use the variables you want to print inline, like this:<br />

echo “Total amount of order is $total.”;<br />

To get the same effect with printf(), you would use<br />

printf (“Total amount of order is %s.”, $total);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!