CodeBlanks Logo Icon CodeBlanks

Summary - Functions

PHP course · Beginner · Lesson 76/116

Build a tax calculator using function declaration and return.

Summary - Functions

In this group you learned to define functions (function), call them, return values with return, work with scope and return arrays. Now we will combine them in a tax calculator.

Scenario: a product price sits in a global $price; the calculateTax function will read it, compute a 20% tax and return it with return.

Exercise Build a tax calculator

Define a global variable with $price = 100;. Define a parameterless function named calculateTax; in the body, first write global $price;, then return the tax with return $price * 0.20;. Finally print with echo calculateTax() . "\n";.

Show example solution
Start with $price = 100;. Define function calculateTax() { global $price; return $price * 0.20; }, then print with echo calculateTax() . "\n";.
Example solution:
<?php
// Start with $price = 100; then write the calculateTax function
$price = 100;
function calculateTax() {
    global $price;
    return $price * 0.20;
}
echo calculateTax() . "\n";

Test yourself

  1. Which is the correct calculateTax function?

    • function calculateTax { global $price; return $price * 0.20; }
    • function calculateTax() { return global $price * 0.20; }
    • function calculateTax() { global $price; return $price * 0.20; }
    • function calculateTax() { $price = global; return $price * 0.20; }
    Show answer

    function calculateTax() { global $price; return $price * 0.20; } — Correct. global $price; brings the outer variable, then return $price * 0.20; gives the tax.

  2. Complete the body of the tax function

    $price = 100;
    
    function calculateTax() {
        ____ $price;
        return $price * 0.20;
    }
    echo calculateTax() . "\n";
    Show answer
    $price = 100;
    
    function calculateTax() {
        global $price;
        return $price * 0.20;
    }
    echo calculateTax() . "\n";
  3. Which is true about this group?

    • A function without return gives null
    • A variable inside a function is visible outside
    • A function can be called only once
    • A function name may start with a digit
    Show answer

    A function without return gives null — Correct. Without return, a function gives null.

All lessons in Beginner