Skip to Content
Learning PHP
book

Learning PHP

by David Sklar
April 2016
Beginner content levelBeginner
550 pages
9h 40m
English
O'Reilly Media, Inc.
Content preview from Learning PHP

Appendix B. Answers to Exercises

Chapter 2

Exercise 1

  1. The opening PHP tag should be just <?php with no space between the <? and php.
  2. Because the string I'm fine contains a ', it should be surrounded by double quotes ("I'm fine") or the ' should be escaped ('I\'m fine').
  3. The closing PHP tag should be ?>, not ??>. Or, if this code were the last thing in its file, the closing PHP tag could be omitted.

Exercise 2

$hamburger = 4.95;
$shake = 1.95;
$cola = 0.85;

$tip_rate = 0.16;
$tax_rate = 0.075;

$food = (2 * $hamburger) + $shake + $cola;
$tip = $food * $tip_rate;
$tax = $food * $tax_rate;

$total = $food + $tip + $tax;

print 'The total cost of the meal is $' . $total;

Exercise 3

$hamburger = 4.95;
$shake = 1.95;
$cola = 0.85;

$tip_rate = 0.16;
$tax_rate = 0.075;

$food = (2 * $hamburger) + $shake + $cola;
$tip = $food * $tip_rate;
$tax = $food * $tax_rate;

$total = $food + $tip + $tax;

printf("%d %-9s at \$%.2f each: \$%5.2f\n", 2, 'Hamburger', $hamburger,
       2 * $hamburger);
printf("%d %-9s at \$%.2f each: \$%5.2f\n", 1, 'Shake', $shake, $hamburger);
printf("%d %-9s at \$%.2f each: \$%5.2f\n", 1, 'Cola', $cola, $cola);
printf("%25s: \$%5.2f\n", 'Food Total', $food);
printf("%25s: \$%5.2f\n", 'Food and Tax Total', $food + $tax);
printf("%25s: \$%5.2f\n", 'Food, Tax, and Tip Total', $total);

Exercise 4

$first_name = 'Srinivasa';
$last_name = 'Ramanujan';
$name = "$first_name $last_name";
print $name;
print strlen($name);

Exercise 5

$n = 1; $p = 2;
print "$n, $p\n";

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

Learning PHP 5

Learning PHP 5

David Sklar
Learning PHP 7

Learning PHP 7

Antonio L Zapata (GBP)
Advanced PHP Programming

Advanced PHP Programming

George Schlossnagle

Publisher Resources

ISBN: 9781491933565Errata PageSupplemental Content