CHAPTER 4
A function is a piece of code that receives data by using a set of variables named parameters, and then processes this data and returns a value. Sometimes functions don’t receive any data at all, and only return a value, or just perform an action and don’t return a value.
To create a function in PHP, we should use the reserved keyword function, followed by the name we want to give to that function. Then, we need to write the code the function will execute within curly braces. The following code shows an example of a function.
Code Listing 26: A Simple PHP User-Defined Function
<?php
function showmessage() { echo "This message was displayed from within a function <br />"; }
showmessage(); ?> |
This function code prints a message and returns no value; a return value is not strictly necessary when defining functions. There’s another issue regarding this code: every time we call the function, the same message is printed. This is not practical, because if we want to print a different message, another function should be created. To deal with cases like this, we need to provide data to the function by using a series of identifiers called parameters.
Parameters in functions are a series of identifiers declared after the function name, enclosed in parentheses. We can declare as many parameters as we need. These parameters are considered variables within the function.
Now, let’s make a better version of the showmessage() function displayed in Code Listing 26.
Code Listing 27: A User-Defined Function with Parameters
<?php
function showmessage($message) { echo "$message <br />"; }
showmessage('This message is displayed by using parameters'); ?> |
A function can return a value to the calling program by employing the return statement. When the return statement is issued, the function execution stops. The following code returns a greeting message from a function.
Code Listing 28: A Function That Returns a Value
<?php function greetingmessage() { date_default_timezone_set("Etc/GMT+7"); $hour = date('H'); $dow = date('N')-1; $namesofdays = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
if ($hour >=0 && $hour < 12) $result = "Good Morning!"; elseif ($hour >= 12 and $hour < 19) $result = "Good afternoon!"; else $result = "Good Evening!";
$result = $result . ", today is $namesofdays[$dow]"; return $result; }
echo greetingmessage();
?> |
We can set function parameters to have a default value, in case the calling program doesn’t pass any value to them. To define default values for parameters, we just place the desired value beside the parameter name, leading by an equal assignment operator (=).
Now, we’re going to modify the greetingmessage() function of the previous sample, in order to display or omit the day-of-week name. By default, if a value is not passed to the corresponding parameter, the day-of-week name will be omitted.
Code Listing 29: Setting Up Default Values for Parameters
<?php function greetingmessage($showdayofweek = false) { date_default_timezone_set("Etc/GMT+7"); $hour = date('H'); $dow = date('N')-1; $namesofdays = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
if ($hour >=0 && $hour < 12) $result = "Good Morning!"; elseif ($hour >= 12 and $hour < 19) $result = "Good afternoon!"; else $result = "Good Evening!";
if ($showdayofweek) $result = $result . ", today is $namesofdays[$dow] <br />"; return $result; }
echo greetingmessage(true); //Shows day-of-week name echo greetingmessage(); //Shows greeting message only
?> |
A function can be called dynamically by storing its name into a string variable. Then, we can use this variable as we would the function name itself. The following sample uses the greetingmessage() function discussed in previous code examples and modifies it to be called dynamically, depending on the current hour.
Code Listing 30: Calling Functions Dynamically
<?php function getgreetingfunction() { date_default_timezone_set("Etc/GMT+7"); $funcnames = array('goodmorning','goodmorning','goodafternoon','goodevening'); $hour = date('H'); return $funcnames[(int)$hour/6]; }
function dayofweekname($daynumber) { $namesofdays = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); return $namesofdays[$daynumber - 1]; }
function goodmorning($showdayofweek = false) { $result = "Good Morning!"; if ($showdayofweek) $result = $result . ", today is " . dayofweekname(date('N')); $result = $result . " <br />"; return $result; } function goodafternoon($showdayofweek = false) { $result = "Good Afternoon!"; if ($showdayofweek) $result = $result . ", today is " . dayofweekname(date('N')); $result = $result . " <br />"; return $result; } function goodevening($showdayofweek = false) { $result = "Good Evening!"; if ($showdayofweek) $result = $result . ", today is " . dayofweekname(date('N')); $result = $result . " <br />"; return $result; }
$functionname = getgreetingfunction();
echo $functionname(); echo $functionname(true);
?> |
As noted in the previous code, we broke down the original function into five smaller ones. The first (greeetingfunction) will return the name of one of the program functions that will submit the greeting message. For doing this, we split the hours of a day into four pieces of six hours each (4 x 6 = 24). Each one of these pieces has a matching item into the $funcnames array.
This array stores the names of the functions that should be executed according to the hour of the day. We assume that the first twelve hours are considered part of the morning, which is from 0 to 11 hours. So, the first two items in the array store the same name. The third and the fourth items store the name for the afternoon and the evening greeting messages, in that order.
To get the proper array index, we divide the current hour returned by the date(‘H’) function by 6. The dayofweekname function returns the day-of-week name, according to the current date. Finally, we store the corresponding greeting message function name into the $functioname variable, and then we execute it by placing the variable name after the echo statement.
PHP has a large set of built-in functions. We can classify these functions into several categories. The most important of them, according to the scope of this book, are displayed in the following list.
The following sections summarize each category of functions in a series of tables, where each table contains the most relevant functions (according to the scope of this book) within that category.
Table 10: Array Functions Listing
Function | Description |
|---|---|
array() | Creates an array |
array_change_key_case() | Returns an array with all keys either in lowercase or uppercase |
array_chunk() | Splits an array into chunks of arrays |
array_combine() | Creates an array by using one array for keys and another array for its values |
array_count_values() | Returns an array with the number of occurrences for each value |
array_diff() | Compares array values and returns the differences |
array_fill() | Fills an array with values |
array_keys() | Returns all keys of any array |
asort() | Sorts an array and maintains index association |
arsort() | Sorts an array in reverse order and maintains index association |
Table 11: Date and Time Functions Listing
Function | Description |
|---|---|
date_date_set() | Sets the date to a given date-time value |
date_format() | Returns a formatted date according to a given format |
date_parse() | Returns an associative array with detailed info about a given date |
date_time_set() | Sets the time to a given value |
time_zone_indentifiers_list() | Returns a numeric index array with all time zones identifiers |
date() | Formats the local time/date |
Table 12: String Functions Listing
Function | Description |
|---|---|
strlen() | Returns the length of a string |
strpos() | Finds and returns the position of the first occurrence of a string within another string |
substr() | Returns a part of a string |
ltrim() | Removes white spaces or other characters from the beginning of a string |
rtrim() | Removes white spaces or other characters from the end of a string |
str_repeat() | Returns a repeated string |
Table 13: Character Functions Listing
Function | Description |
|---|---|
ctype_alnum() | Checks for alphanumeric characters in a string |
ctype_alpha() | Checks for alphabetic characters in a string |
ctype_digit() | Checks for numeric characters in a string |
ctype_lower() | Checks for lowercase characters in a string |
crtype_upper() | Checks for uppercase characters in a string |
ctype_cntrl() | Check for control characters (such as Tab) in a string |
Table 14: File System Functions Listing
Function | Description |
|---|---|
copy() | Creates a copy of a file |
delete() | Deletes a file |
dirname() | Returns the directory portion for a given path |
file() | Reads an entire file into an array |
file_exists() | Checks whether a file or directory exists |
basename() | Returns the filename portion of a given path |
Table 15: Directory Functions Listing
Function | Description |
|---|---|
chdir() | Changes the current directory |
dir() | Opens a directory handle and returns an object |
closedir() | Closes a directory previously opened with dir() |
getcwd() | Returns the current working directory |
readdir() | Reads an entry from a directory handle |
scandir() | Returns a list of all files and directories inside a specified path |
Being able to reuse code is an important aspect of application development. Reusing code gives the developer an easy mechanism to maintain complex applications with reduced effort. In PHP, we can reuse code by using file inclusion.
File inclusion allows us to include the content of a PHP file into another file, before the server executes it. There are two functions that help us to perform file inclusion:
Tip: Use the require() function instead of include() to prevent the script’s execution when there is a problem with file inclusion.
To illustrate file inclusion, we’re going to split the code sample detailed in the “Calling functions dynamically section” into two files. The first one will contain all function declarations, and it will be named commonfunctions.php.
Code Listing 31: commonfunctions.php
<?php function getgreetingfunction() { date_default_timezone_set("Etc/GMT+7"); $funcnames = array('goodmorning','goodmorning','goodafternoon','goodevening'); $hour = date('H'); return $funcnames[(int)$hour/6]; }
function dayofweekname($daynumber) { $namesofdays = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); return $namesofdays[$daynumber - 1]; }
function goodmorning($showdayofweek = false) { $result = "Good Morning!"; if ($showdayofweek) $result = $result . ", today is " . dayofweekname(date('N')); $result = $result . " <br />"; return $result; } function goodafternoon($showdayofweek = false) { $result = "Good Afternoon!"; if ($showdayofweek) $result = $result . ", today is " . dayofweekname(date('N')); $result = $result . " <br />"; return $result; } function goodevening($showdayofweek = false) { $result = "Good Evening!"; if ($showdayofweek) $result = $result . ", today is " . dayofweekname(date('N')); $result = $result . " <br />"; return $result; } ?> |
The second file will contain the script to be executed. It will be named usingfileinclusion.php.
Code Listing 32: usingfileinclusion.php
<?php require("commonfunctions.php"); $functionname = getgreetingfunction();
echo $functionname(); echo $functionname(true);
?> |
This code sample shows the use of the require() function. This function takes the content of commonfunctions.php and inserts it into the script. Now when we call getgreetingfunction(), it is available to the script even when it is not explicitly defined in usingfileinclusion.php.
This chapter explored topics related to functions. A function is a piece of code that receives data by using a set of variables named parameters, and then processes this data and returns a value. In PHP, we have user-defined and built-in functions. A user-defined function is created by the developer by using the reserved keyword function, followed by the name of the function.
When you need to pass data to a function, you should use a series of identifiers called parameters. Parameters are declared after the function name and enclosed in parentheses. You can declare as many parameters as you need. All these parameters will be considered variables within the function. A function can return a value to the calling program employing the return statement.
We can set functions’ parameters to have a default value, in case the calling program doesn’t pass any value to any of them. Default values are defined by placing the desired value at the right side of the parameter name, leading with an equal assignment operator (=).
A function can be called dynamically by storing its name into a string variable. We can use this variable as we would the function name itself.
PHP has a large set of built-in functions that can be classified in categories. The categories discussed in this chapter are: array functions, which allow the developer to interact with and manipulate arrays; date and time functions, which get the date and time from the server in which scripts are running; string functions, which allow the developer to manipulate strings; character functions, which check whether a string or character falls into certain class; file system functions, which access and manipulate the file system; and directory functions, which are used to manipulate directories.
Reusing code is important for maintaining complex applications with minimal effort. PHP allows the reuse of code by means of file inclusion. File inclusion is the mechanism used to insert the content of a PHP file into another one, and it is performed by two functions: include(), which copies all the text in the specified file into the script, generating a warning message when a problem occurs; and require(), which is similar to include(), except that it halts script execution when a problem occurs.