SakhaliaNetHome PageMilitary HistoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Exercises (I)

PHP Exercise #1

Cost of meal (I)

Calculate the total cost of a meal composed of two hamburgers (4.95 € each), a chocolate milkshake (1.95 €) and a Coca Cola (0.85 €), being the IVA 7.5% and leaving a 16% tip before taxes.

<?php
$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";
?>
Total cost of the meal is $15.6845

PHP Exercise #2

Cost of meal (II)

Calculate the total cost of a meal composed of two hamburgers (4.95 € each), a chocolate milkshake (1.95 €) and a Coca Cola (0.85 €), being the IVA 7.5% and leaving a 16% tip before taxes. Print a bill with format that shows price, quantity and cost for every article, and the total price for the meal with the drinking included, before the IVA, after the IVA, and after the IVA and the tip. The prices must appear vertically aligned.

<?php
$hamburger = 4.95;
$milkshake = 1.95;
$cola = .85;
$food = 2 * $hamburger + $milkshake + $cola;
$tax = $food * .075;
$tip = $food * .16;
$total = $food + $tax + $tip;
printf("%1d %9s at \$%.2f each: \$%.2f\n", 2, 'Hamburger', $hamburger, 2 * $hamburger);
print nl2br("\n");
printf("%1d %9s at \$%.2f each: \$%.2f\n", 1, 'Milkshake', $milkshake, 1 * $milkshake);
print nl2br("\n");
printf("%1d %9s at \$%.2f each: \$%.2f\n", 1, 'Coca Cola', $cola, 1 * $cola);
print nl2br("\n");
printf("%25s: \$%.2f\n", 'Food and Drink Total', $food);
print nl2br("\n");
printf("%25s: \$%.2f\n", 'Total with Tax', $food + $tax);
print nl2br("\n");
printf("%25s: \$%.2f\n", 'Total with Tax and Tip', $food + $tax + $tip);
?>
2 Hamburger at $4.95 each: $9.90
1 Milkshake at $1.95 each: $1.95
1 Coca Cola at $0.85 each: $0.85
Food and Drink Total: $12.70
Total with Tax: $13.65
Total with Tax and Tip: $15.68

PHP Exercise #3

Name and surname

Set a name and a surname in two variables, and print a string that contains the name and the surname separated by a space, and print as well the lenght of the string.

<?php
$first_name = 'James';
$last_name = 'McCawley';
$full_name = "$first_name $last_name";
print $full_name . ' (' . strlen($full_name) . ' characters long)';
?>
James McCawley (14 characters long)

PHP Exercise #4

Increment and exponent

Write a program that uses the operator ++ and the operator *= to print the numbers from 1 to 5 and the powers of 2 from 2(2exp1) to 32(2exp5).

<?php
$i = 1; $j = 2;
print "$i [$j]\n";
$i++; $j *= 2;
print "$i [$j]\n";
$i++; $j *= 2;
print "$i [$j]\n";
$i++; $j *= 2;
print "$i [$j]\n";
$i++; $j *= 2;
print "$i [$j]\n";
?>
1 [2] 2 [4] 3 [8] 4 [16] 5 [32]