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.
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:
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:
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:
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:
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.
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:
$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.
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:
Call your initArray() to fill your $cards array if you haven't already done so.
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.
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 a list of all the cards left in the $cards array
in the same format as described above.