PHP Logo

Chapter 5 - Creating and Using Functions

By: Albert Ritzhaupt

 

 


Chapter Topics 

Why Functions? 

As you have probably noticed, web programming requires a great deal of problem solving skills.  Many of the problems that you solve with computer programs can be reused.  What's more, most computer programs will require that the same code be executed at different locations in your program.  When you approach a complicated problem, it is good practice to break the problem into smaller sub problems.  You may then solve the smaller sub problems and rebuild the smaller solutions into one large solution.  This process is called functional decomposition.

In PHP, the sub problems are implemented using functions.  Functions are little solutions to small problems that can be called in your program.  As a web programmer, you can create your own functions, which are called user-defined functions, or use the functions available to you in PHP.  This chapter will focus on instructing you on how to create functions, how to call functions, and how to find functions that are already available to you.

To provide a you a basic understanding of a function, we should revisit functional notation from your algebra class.  If you remember, when we define a function in algebra, we have arguments (parameters), and a resulting value.  For instance, look at the following function:

f(x) = 2x + 1

The function shown in the figure is pretty simple.  It accepts a parameter (x) as input, multiplies that input by two, and adds one.  Keep in mind, a function can only result to one value - otherwise it would not be a function (vertical line test).  If you were to provide the value 5 as a parameter to this function, the result would be 11.  In web programming, we provide parameters to a function, a process is executed, and generally, a value is returned.

back to top

Anatomy of a Function 

In order to create and use functions in PHP, you should understand the anatomy of a function.  Using functions is essential to creating robust programs in PHP because most of the things you need to do, such as reading from a file or accessing a database, require the use of functions.  The syntax for a function in PHP is pretty straight-forward and is shown in the figure below (PHP function, 2005). 

An illustration of function anatomy.

In the figure, you will notice that three distinct areas are emphasized.  The first item (labeled 1) is known as the function name.  The function name is the name you will use to call the function.   The second item (labeled 2) is the parameter list.  The parameter list includes the inputs that you must provide to the function when it is called.  Some functions can be called without providing any parameters.  The third and last item (labeled 3) is the return statement.  The return statement is the value that is returned by the function.  A return statement is not required because the function may not return a value.

Now that we have gone over the anatomy of a function, we need to understand how to call a function.  Keep in mind that you must create the function before you call it.  Calling a function is as simple as providing the function name with the necessary parameter list.  The example below shows a function named sum and shows how to call the function.



<?php
function sum($var1, $var2)
{
$sum = $var1 + $var2;
return $sum;

}
$result = sum(50,40);
echo $result;
?>

This is a simple example of a function.  The function name is sum.  The sum function accepts two parameters: $var1 and $var2.  The function's process is to add the two parameters and return the result.  As you can see, the values 50 and 40 are provided as the value of the parameters.  The variable $var1 will assume the value of 50 and  $var2 to the value 40.  The sequence of the parameter list is important and parallels to the function's anatomy.  The two values are added together and assigned to the variable $sum, which is returned to the calling statement and assigned to the variable $result.  Finally, the variable $result is displayed.  Look at the example program below to see the result.

>>Program Example 1

back to top

Function Overloading 

As a general rule, you are not supposed to create functions with the exact same name and parameter list.  However, in some cases, creating functions with the same function name and a different parameter list is useful.  When the program is executed, it will determine which function to execute based on the parameter list.  For example, imagine creating three functions all with the same name, sum.  Now imagine that each of the three functions accepted a different number of parameters: one for adding two numbers, one for adding three numbers, and one for adding four numbers.  It would not make sense to give the functions different names because that all do the same thing - add numbers.  Therefore the use of method overloading is useful and meaningful in this case.  You will see many different examples of function overloading in the subsequent sections and chapters.   However, it is critical to keep in mind that this can only be accomplished using the object-oriented features of PHP which is outside the scope of this text.

back to top

Using PHP's Internal Functions 

A good PHP programmer learns to find functions that are already built to solve their problems.  The PHP programming language has a multitude of functions available for any number of tasks.  Furthermore, there are a number of electronic resources to help you find and use the functions.  The remaining portion of this chapter will be dedicated to: (1) teaching you how and where to find information about functions available to you, and (2) how to use some of these functions to solve problems. 

Probably the most important resource for you to become familiar with is the official PHP web site.  This website provides all the resources for the language and was the primary resource for the creation of this text. The official PHP website is: www.php.net.  This website not only provides technical documentation, it allows you to search the content using keywords, access to discussion boards, and access user group listings.  You will use this website frequently to look up examples of using functions as well as the technical documentation for those functions.

When you look up a function using the PHP website, it provides you the basic information about the function, which includes: (1) the function's name, (2) the function's parameters, (3) the function's return type and value, (4) a short description, and (5) examples of the function.  All of this information can be used to help you effectively use the PHP programming language.

back to top

Popular String Functions 

It is very common for a web programmer to use PHP string functions to manipulate strings for some intended purpose.   We will explore more string functions after we have used arrays.  In addition to the strings we discuss here, you should explore the technical documentation for other string functions.  The string functions that you should be aware of now include the following:

  • stolen(string) - returns the number of characters in the string
  • str_replace(search_string, replace_string, string)- returns the result of a search and replace applied to a string
  • trim(string) - returns the string after it removes white space from both sides
  • substr(string, start_int, end_int) - returns the result of parsing a string from the start_int to the end_int
  • strtoupper(string) - returns the string after it converts the string to upper case

The program shown in the figure below manipulates a string using each of these functions.  Pay special attention to the result of each of the function calls.

<?php
$someString=" aFileName.txt ";
$length=strlen($someString);
echo "-$someString-<br>";


echo "someString length is $length<br>";
$someString=trim($someString);
$length=strlen($someString);
echo "-$someString-<br>";
echo "someString after trim is $length<br>";
$someString=str_replace("txt", "doc", $someString);
echo "someString after replace is $someString<br>";
$someString=substr($someString, 0, 9);
echo "someString after substr is $someString<br>";
$someString=strtoupper($someString);
echo "someString in upper case is $someString<br>";
?>

The first thing to notice in this program is that the string initially assigned to the variable $someString has an extra space on each side, which adds up to a total of 15 characters.  After the trim function is used on the string, the extra white space on each side is removed, which is 13 characters.  You can verify this by looking at the result of the strlen function.

The next function that is called is the str_replace function, which searches for the string "txt" and replaces it with the string "doc".  Next, the substr (sub string) function is called.  The substr function parses the string from 0 to 9, which effectively removes the ".doc" from the string, resulting in "aFileName".  Finally, the strtoupper function is called, which converts the string to all upper case.  

>>Program Example 2

back to top

PHP Mail Function 

Sometimes we use PHP to send emails to people, such as notifications or confirmations.  You likely have received an email confirmation after an online purchase.  This email is not generated by a human being - it is computer generated.  In PHP, we can use the mail function to send emails automatically.  Keep in mind, this is the type of function that is used to send spam.  The following is the PHP source code for a program that will send an email using the PHP mail function.

<?php
$subject=$_POST['subject'];
$email=$_POST['email'];
$body=$_POST['body'];
if ($subject != "" && $email != "" && $body != "")
{
mail($email, $subject, $body, "From: $email");
}
?>
<form action="example3.php" method="POST">
<b>To:</b> <input name='email'><br>
<b>Subject:</b><input name='subject'><br>

<b>Body:</b><textarea name='body'></textarea><br>
<input type='submit' value='send'>
</form>

This program accepts the parameters from the HTML form, checks that each of the fields contain information, and sends the information using the mail function.  There are some severe legal penalties for sending spam or sending emails posing to be another person.  Please keep in mind that the system can be set up to trace who wrote the programs that generate the emails.  

>>Program Example 3  

back to top

PHP Date Function 

The last function we are going to use in this chapter is the date function, which is extremely useful in web programming.  The date function can be used to format a date according to a predefined structure chosen by you.  In order to use the date function, you have to learn the format characters.  The table below summarizes many of the format characters available to properly format dates (PHP date, 2005).

Format Character Description Example
Day
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week
W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
Month
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) Examples: 1999 or 2003
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
Time
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59

You can use any combination of these format characters to generate a desired result.  There are many different established date formats used in the United States and internationally that you are probably familiar with.  The example program below uses many of the formating characters to show you how these format characters.

<?php
echo date("F dS, Y");
echo "<br>";
echo date("m/d/Y");
echo "<br>";
echo date("m/d/Y h:i:s A");
echo "<br>";
echo date("M. dS, Y");
?>

Although this example only uses a fraction of the available format characters available, it does show how you can create many different date formats. You can see an example of this program below:

>>Program Example 4  

back to top

Your Fifth Program

This section will provide the steps for you to create your fifth PHP program.  You are going to create a simple program

  1. First create a file named "fifth.html" in a directory that is recognized by the web server. The file should contain the following information:

    <html>
    <form action="program5.php" method="post">
    Number 1: <input name="num1"><br>
    Number 2: <input name="num2"><br>
    Number 3: <input name="num3"><br>
    <input type="Submit" value="Add">
    </form>
    </html>

  2. Now let's create the source code for the program.  Create a file named "program5.php" in the same directory as "fifth.html".  The file should contain the following information:

    <?php 
    function add2($x, $y)
    {
    return $x + $y;
    }

    function add3($x, $y, $z)
    {
    return $x + $y + $z;
    }
    ?>

    <?php
    $x=$_POST['num1'];
    $y=$_POST['num2'];
    $z=$_POST['num3'];

    if($x != "" && $y != "" && $z != "")
    {
    $out = add3($x, $y, $z);
    }elseif ($x != "" && $y != ""){
    $out = add2($x, $y);
    }elseif ($x != "" && $z != ""){
    $out = add2($x, $z);
    }elseif ($y != "" && z != ""){
    $out = add2($y, $z);
    }else{
    $out = "must provide at least two values";
    }

    echo "OUTPUT: $out";
    ?>

  3. After you have created the file and put the information into the files, save your work, and change the permissions of the files to:

    prompt$: chmod 704 fifth.html
    prompt$: chmod 705 program5.php

  4. Open the URL to the location where you saved the file (fifth.html) and you should be able to submit values.  

Notice that the source code will accommodate for every case.  For example, a user can put a value in number 1 and number 3 or in number 2 and number 3.  Each case is accounted for using if statements.  Also, notice that the function declarations appear before they are         used.  It is good practice to declare all your functions at the top of the program.

Congratulations! You have completed the fifth chapter. You can now take the online assessment, complete the fifth activity, and move to the next chapter. 

>>Take the Online Quiz

back to top

Activity 5

Create an html file with a form to accept a date in the following format as a textbox: MM/DD/YYYY.  The form should submit to a program with a function named changeDate.  The changeDate function should accept the function in the format provided and translate it into a long date format: MMMMMM DD, YYYYY.  For example, if the date entered was "10/12/2005", the result of the function should be "October 12, 2005".  The new date format should be output to the screen. 

Chapter References 

back to top

Previous section Next section

 

Copyright Albert Dieter Ritzhaupt. All Rights Reserved.