Overview of This Lesson

Refresh this page because I am probably still making changes to it.

Functions in PHP are similar to functions in other languages, although the syntax for creating functions is similar to JavaScript. In more recent versions of PHP you can use function expressions and arrow functions, but this lesson focuses only on function declarations.

Resources

PHP Manual: Functions.

Pre-requisites

Before doing this lesson, make sure you're familiar with PHP's Variables and Data Types and Operators and Control Structures. It would also help if you were also familar with Arrays in PHP.

Function Declarations

Functions in PHP (often called "methods" in other languages) can be declared or defined as user-defined functions - in this case, the "user" is a PHP programmer - using the function keyword.

function functionName() {
// function code
}

Function names or identifiers follow the same rules as other PHP identifiers and follow the same or similar standards to languages like Java.

To call a function with no arguments:

functionName();

To call a function with arguments:

functionName(arg1, arg2, ... )

To call a function that returns a value:

$result = functionName();

or with arguments:

$result = functionName(arg1, arg2, ...)

Of course, a function's return value could be passed to another function as an argument:

functionTwo(functionOne());

Parameters can be specified inside the parentheses, without the data type:

function functionName($param1, $param2, ...) {
    // function code
}

To write a function that returns a value, simply include the relevant return statements inside the function:

function calcTip($billAmt, $tip) {
    return $tip / 100 * $billAmt;
}

Variable-Length Argument Lists

Like Java, PHP suports variable-length argument lists. The variable-length paramter must be preceeded by the ... ellipses symbol. Within the function, treat the parameter as if it were an array:

function average(...$numbers) {
    $sum = 0;
    foreach ($numbers as $num) {
        $sum += $num;
    }
    return $sum / count($numbers);
}
    
echo "<p>".average(50, 45, 49)."</p>";
echo "<p>".average(81.1, 74.5, 77.9, 80.0, 93.5)."</p>";

Output:

48
81.4

Variable Scope

By default, variables are visible in the context in which they are defined. For example, a variable defined in a PHP file, outside of any function is visible anywhere in that file (and also in any included/required files. However, a variable defined or referenced inside a function is always local to that function.

Since PHP is a loosely-typed language, this can cause some unexpected results. For example, the following code will print nothing:

$varA = 5;

function foo() {
  echo $varA;
}

// calling function foo()
foo();

Why? Because when you refer to a variable inside a programmer-defined function, you always refer to the most local one. Referring to $varA inside foo() will automatically refer to a local $varA. Since there is no $varA declared inside foo(), $varA is nothing: Inside the foo() method, the $varA referenced on the first line doesn't even exist.

If you want a "global variable" declared outside a function and available inside the function without passing it as an argument, you need to use the "global" keyword:

$varA = 5;

function foo() {
  global $varA;
  echo $varA;
}

// calling function foo()
foo();

Using the keyword global in front of $varA inside the foo() function tells the function that $varA is referring to the variable $varA defined earlier, not to a new variable that is local to foo().

Re-Using Functions

As you know from prior experience, functions should be modular, abstract, and re-usable. You can easily make your functions re-usable by putting them in an external PHP file and then including or importing that file into any other page/file you like. You learned about includes and include/require functions in the Intro to PHP lesson. For example, say we have the following PHP file called rooms.php:

<?php 
    /* rooms.php */
    
    // room name => area of room in m^2
    $rooms = [
        "e202" => 147.0,
        "e200" => 308.0,
        "e210" => 77.5,
        "e205" => 545.25
    ];
        
    // get the capacity of a room basedon its area and 
    // whether or not it's a lab room
    function getCapacity($area, $isLab) {
        $numPeople = 4;
        if ($isLab) {
            $numPeople = 2;
        }
        return (int)($area / $numPeople);
            
    }
    
    // get an HTML table of room data
    function displayRoomTable($array) {
        
        // start the table
        $output = "<table>\n<tr><th>Room</th><th>Area</th><th>Capacity</th></tr>";
        
        // for each room/area, add a row in the table
        foreach ($array as $room => $area) {
            $output .= "<tr><td>$room</td><td>$area</td><td>"
                .getCapacity($area, false)."</td></tr>\n";
        }
        $output .= "</table>\n";  // close the table
        
        return $output;
    }     
?>

This file has an array called $rooms with key-value pairs: The key is the room number and the value is the area in square metres. A getCapacity() function determines the capacity for rooms and labs by using the area (regular rooms allow for 4 people per square metre, labs allow for 2 people per square metre). The displayRoomTable() accepts an array of rooms and uses the data to construct an HTML table that displays the room number, area, and capacity.

We can re-use all or some of this file by adding an include() or require() to any other page (note that you learned about includes in the Intro to PHP lesson). In this example, the index.php file below is our main page, and it reads/uses the code defined in the rooms.php file:

<!doctype html>
<!-- index.php -->
<?php 
    include("rooms.php");
?>
<html lang="en">
    
    <head>
        <meta charset="utf-8">
        <title>Room Capacity</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    
    <body>
        <header>
            <h1>Room Capacity for Offices</h1>
        </header>

        <main>
            
            <?= displayRoomTable($rooms) ?>
            
        </main>
        <footer>
            <address>&copy; 2017 Wendi Jollymore</address>
        </footer>
    </body>
</html>

On line 4 we include the rooms.php file. On line 21, we call the displayRoomTable() function so we can display the capacity table. Notice that we can also freely access the $rooms array defined in the rooms.php file!

This is one very simple example of how you might use PHP to create template pages.

Callbacks

PHP supports callback functions, so you can pass a function to another function. This is handy for a lot of PHP's built-in functions. To use a callback specify the name of the function as a string literal when you pass it as the argument:

<?
    function isFail($n) {
        return $n < 50;
    }
    function isPass($n) {
        return $n >= 50;
    }
    function isProbation($n) {
        return $n < 60;
    }
                
    $grades = [78.5, 66, 43.9, 71.1, 57.6, 48.9];
    $fails = array_filter($grades, "isFail");
    $probations = array_filter($grades, "isProbation");
    $passes = array_filter($grades, "isPass");
    var_dump($fails);
    echo "<br>";
    var_dump($probations);
    echo "<br>";
    var_dump($passes);
?>

Output:

array(2) { 
    [2]=> float(43.9) 
    [5]=> float(48.9) 
}
array(3) { 
    [2]=> float(43.9) 
    [4]=> float(57.6) 
    [5]=> float(48.9) 
}
array(4) { 
    [0]=> float(78.5) 
    [1]=> int(66) 
    [3]=> float(71.1) 
    [4]=> float(57.6)
}

There are several array functions that can use callbacks (you just saw an example of one):

Exercises

1. A summation of a series of numbers from 1 to n can be calculated with the formula: (n(n+1))/2 Write a function creates and initializes a variable for n, calculates the summation of the numbers from 1 to n, and then displays the result. For example: The sum of values from 1 to 10 is 55. Your output should be enclosed in paragraph or div tags.

2. A program calculates a person's weekly pay based on the following: If the hours worked are less than or equal to 40, the person receives 10 dollars per hour; otherwise, the person receives 10 dollars for the first 40 hours and then 15 dollars for the hours they work over 40. Use a function that calculates and returns the amount to pay based on the number of hours. Your program should initialize a variable with the number of hours worked, and then calculate the weekly pay. Display your result.

3. Write a program that uses function to determine the maximum number of days in a month. Initialize a variable for the month number and the 4-digit year. Note that a year is a leap year if it is evenly divisible by 400 or evenly divisble by 4 and not 100.

4. a. Write a function called gradePoints() that uses the Sheridan Grading System to determine the grade points to assign to a specific final grade.

4. b. Add code to the previous question to use the array_map() function to create an array of grade points that corresponds to an array of grades. For example, if your grades array contains [78.5, 66, 43.9, 71.1, 57.6, 48.9], then your grade points array will contain [3.3, 2.5, 0, 3.0, 1.5, 0]

4. c. Add a loop to the previous question that displays the grades array and the grade points array in a table: the first column contains the grades and the second column contains the grade points for each grade.

a table of grades and grade points
Output from the grade points exercise

5. a. Generate a random number between 1 and 100. Display a message "This is a prime number." if the number generated is prime. Use a function isPrime() that returns true if the number is prime and false if the number isn't prime.

5. b. Create an array of numbers (you can fill your array with some random numbers, if you want, see rand()). Use array_filter() to obtain an array containing only the prime numbers. Display your prime numbers array.

6. Write a program that uses array_reduce() to calculate the sum of an array's elements as 1/i2 were i is the array element value. For example, if an array contains [2, 4, 6, 8] the sum would be 0.356 (1/4 + 1/16 + 1/36 + 1/64).

7. Create a page that draws 5 random playing cards:

  1. Start with these three arrays:
    $suits = [
        "C" => "Clubs",
        "D" => "Diamonds",
        "H" => "Hearts",
        "S" => "Spades"	
    ];
    $values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];
    
    $cards = [];

    $suits contains the four suits in a standard deck of playing cards
    $values contains the values each suit has in a standard deck of playing cards
    $cards is an empty array that will contain one element for each card in a standard deck of playing cards.

  2. Write a function initArray() that uses the global variables $suits, $values, and $cards: Fill the $cards array with entries for each card in a standard deck of cards. Each element of $cards is an array where element 0 is the value and element 1 is the suit. For example, if you want to test your function and see if your array was initialized correctly, a var_dump of your $cards array after it has been filled will contain:
    array(52) { 
    [0]=> array(2) { 
        [0]=> int(1) 
        [1]=> string(1) "C"
    } [1]=> array(2) { 
        [0]=> int(2) 
        [1]=> string(1) "C" 
    } [2]=> array(2) { 
        [0]=> int(3) 
        [1]=> string(1) "C" 
    } [3]=> array(2) { 
        [0]=> int(4) 
        [1]=> string(1) "C" 
    } [4]=> array(2) { 
        [0]=> int(5) 
        [1]=> string(1) "C" 
    } [5]=> array(2) { 
        [0]=> int(6) 
        [1]=> string(1) "C" 
    } [6]=> array(2) { 
        [0]=> int(7) 
        [1]=> string(1) "C" 
    } [7]=> array(2) { 
        [0]=> int(8) 
        [1]=> string(1) "C" 
    } [8]=> array(2) { 
        [0]=> int(9) 
        [1]=> string(1) "C"
    } [9]=> array(2) {
        [0]=> int(10) 
        [1]=> string(1) "C" 
    } [10]=> array(2) { 
        [0]=> string(1) "J" 
        [1]=> string(1) "C" 
    } [11]=> array(2) { 
        [0]=> string(1) "Q" 
        [1]=> string(1) "C" 
    } [12]=> array(2) { 
        [0]=> string(1) "K" 
        [1]=> string(1) "C" 
    } [13]=> array(2) { 
        [0]=> int(1) 
        [1]=> string(1) "D" 
    } [14]=> array(2) { 
        [0]=> int(2) 
        [1]=> string(1) "D"
    } [15]=> array(2) { 
        [0]=> int(3) 
        [1]=> string(1) "D" 
    } [16]=> array(2) { 
        [0]=> int(4) 
        [1]=> string(1) "D" 
    } [17]=> array(2) { 
        [0]=> int(5) 
        [1]=> string(1) "D" 
    } [18]=> array(2) { 
        [0]=> int(6) 
        [1]=> string(1) "D" 
    } [19]=> array(2) { 
        [0]=> int(7) 
        [1]=> string(1) "D" 
    } [20]=> array(2) { 
        [0]=> int(8) 
        [1]=> string(1) "D" 
    } [21]=> array(2) { 
        [0]=> int(9) 
        [1]=> string(1) "D" 
    } [22]=> array(2) { 
        [0]=> int(10) 
        [1]=> string(1) "D" 
    } [23]=> array(2) { 
        [0]=> string(1) "J" 
        [1]=> string(1) "D" 
    } [24]=> array(2) { 
        [0]=> string(1) "Q" 
        [1]=> string(1) "D" 
    } [25]=> array(2) { 
        [0]=> string(1) "K" 
        [1]=> string(1) "D" 
    } [26]=> array(2) { 
        [0]=> int(1) 
        [1]=> string(1) "H" 
    } [27]=> array(2) { 
        [0]=> int(2) 
        [1]=> string(1) "H" 
    } [28]=> array(2) { 
        [0]=> int(3) 
        [1]=> string(1) "H" 
    } [29]=> array(2) {
        ... etc.. you get the idea...
  3. Call your initArray() to fill your $cards array if you haven't already done so.
  4. Pick 5 cards from your array at random and store then in an array called $hand. After a card is chosen, remove it from the $cards array so that it's not chosen again.
  5. Display the contents of the $hand on the screen in the form
    value of suitname
    where value is the card value and suitname is the full name of the suit (e.g. "Diamonds" not "D")
    display of 5 random cards e.g. Q of Hearts, 2 of Clubs
    Five random cards chosen
  6. Display a list of all the cards left in the $cards array in the same format as described above.