Appendix C. Answers To Exercises

Chapter 2

Exercise 1:

  1. The opening PHP tag should be <?php. There should not be a space between <? and php.

  2. The string 'I'm fine' should either be enclosed in double quotes (”I'm fine“) or the apostrophe should be escaped ('I\'m fine').

  3. The closing PHP tag should be ?>, not ??>.

Exercise 2:

$hamburger = 4.95;
$milkshake = 1.95;
$cola = .85;
$food = 2 * $hamburger + $milkshake + $cola;
$tax = $food * .075;
$tip = $food * .16;
$total = $food + $tax + $tip;
print "Total cost of the meal is \$$total";

Exercise 3:

$hamburger = 4.95;
$milkshake = 1.95;
$cola = .85;
$food = 2 * $hamburger + $milkshake + $cola;
$tax = $food * .075;
$tip = $food * .16;
printf("%1d %9s at \$%.2f each: \$%.2f\n", 2, 'Hamburger', $hamburger, 2 * $hamburger);
printf("%1d %9s at \$%.2f each: \$%.2f\n", 1, 'Milkshake', $milkshake, $milkshake);
printf("%1d %9s at \$%.2f each: \$%.2f\n", 1, 'Cola', $cola, $cola);
printf("%25s: \$%.2f\n", 'Food and Drink Total', $food);
printf("%25s: \$%.2f\n", 'Total with Tax', $food + $tax);
printf("%25s: \$%.2f\n", 'Total with Tax and Tip', $food + $tax + $tip);

Exercise 4:

$first_name = 'James';
$last_name = 'McCawley';
$full_name = "$first_name $last_name";
print $full_name;
print strlen($full_name);

Exercise 5:

$i = 1; $j = 2;
print "$i $j";
$i++; $j *= 2;
print "$i $j";
$i++; $j *= 2;
print "$i $j";
$i++; $j *= 2;
print "$i $j";
$i++; $j *= 2;
print "$i $j";

Chapter 3

Exercise 1:

  1. false

  2. true

  3. true

  4. false

  5. false

  6. true

  7. true

Exercise 2:

Message 3.Age: 12. ...

Get Learning PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.