25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

84 ” Strings And Patterns<br />

Formatting Strings<br />

<strong>PHP</strong> provides a number of different functions that can be used to format output in a<br />

variety of ways. Some of them are designed to handle special data types—for example,<br />

numbers of currency values—while others provide a more generic interface for<br />

formatting strings according to more complex rules.<br />

Formatting rules are sometimes governed by locale considerations. For example,<br />

most English-speaking countries format numbers by using commas as the separators<br />

between thousands, and the point as a separator between the integer portion<br />

of a number and its fractional part. In many European countries, this custom is reversed:<br />

the dot (or a space) separates thousands, and the comma is the fractional<br />

delimiter.<br />

In <strong>PHP</strong>, the current locale is set by calling the setlocale() function, which takes<br />

two parameters: the name of the locale you want to set and a category that indicates<br />

which functions are affected by the change. For example, you can affect currency<br />

formatting (which we’ll examine in a few paragraphs) to reflect the standard US rules<br />

by calling setlocale() as in the following example:<br />

setlocale (LC_MONETARY, ’en_US’);<br />

Formatting Numbers<br />

Number formatting is typically used when you wish to output a number and separate<br />

its digits into thousands and decimal points. The number_format() function, used for<br />

this purpose, is not locale-aware. This means that, even if you have a French or<br />

German locale set , it will still use periods for decimals and commas for thousands,<br />

unless you specify otherwise.<br />

The number_format() function accepts 1, 2 or 4 arguments (but not three). If only<br />

one argument is given, the default formatting is used: the number will be rounded<br />

to the nearest integer, and a comma will be used to separate thousands. If two arguments<br />

are given, the number will be rounded to the given number of decimal places<br />

and a period and comma will be used to separate decimals and thousands, respectively.<br />

Should you pass in all four parameters, the number will be rounded to the<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)

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

Saved successfully!

Ooh no, something went wrong!