<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$number = 1234;
printf ("Binary: %b<br />", $number);
printf ("Character: %c<br />", $number);
printf ("Decimal: %d<br />", $number);
printf ("Floating-point: %f<br />", $number);
printf ("Floating-point: %.2f<br />", $number);
printf ("Octal: %o<br />", $number);
printf ("String: %s<br />", $number);
printf ("Hex: %x<br />", $number);
printf ("Hex: %X<br /><br />", $number);
$fruits = array('apples' => 0.75, 'pears' => 1.10, 'oranges' => 0.33);
printf("The prices are \$%.2f for apples, \$%.2f for pears,
and \$%.2f for oranges.<br />", $fruits[apples], $fruits[pears], $fruits[oranges]);
echo "<p>Another way of printing:</p>";
// %6.2 means that a floating point number will be given 4 places in the display
// with two places behind the decimal point.
echo "<pre>";
printf("\$%4.2f<br />", $fruits[apples]);
printf("\$%4.2f<br />", $fruits[pears]);
printf("\$%4.2f<br />", $fruits[oranges]);
echo "</pre>";
echo "<p>Format the output:</p>";
echo "<pre>";
// %-20s defnes a width specifier of 20 characters with the output to be left-justified.
// %20s sets up a right-aligned field with of 20 characters.
printf("%-20s%20s<br />", "Name", "Price");
// %'=40s draws a line containg = characters for 40 characters wide.
printf("%'=40s<br />", "");
foreach ($fruits as $key=>$val) {
printf("%-18s%19.2f<br />", $key, $val);
}
echo "</pre>";
echo "<p>Format the output using sprintf():</p>";
$output = sprintf("The prices are \$%.2f for apples, \$%.2f for pears,
and \$%.2f for oranges.<br />", $fruits[apples], $fruits[pears], $fruits[oranges]);
echo $output;
?>
</p>
</body>
</html>
|