Lesson 9: Functions
Ak Patel
---
What is a function?
A function process inputs and returns an output. It can be useful if, for example, you have a wide range of data you have processed or if you have calculations or routines that must be performed many times.A function has the following syntax:
Function Name(list of parameters) {
Statement
}
function AddOne($x) { $x = $x + 1; echo $x; }
echo AddOne(34);
The example above processes a number, but functions can work with text, dates or anything else. You can also create functions that are called by many different parameters. In this lesson you will see different examples of functions.
Example 1: Function with more parameters
As mentioned above, you can easily create a function that can be called with more parameters. In the next example, we'll create a function that is called with three numbers and then returns the value of the three numbers added together:<html> <head> <title>Functions</title> </head> <body> <?php function AddAll($number1,$number2,$number3) { $plus = $number1 + $number2 + $number3; return $plus; } echo "123 + 654 + 9 equals " . AddAll(123,654,9); ?> </body> </html>
Example 2: English date and time
Let us try to make a slightly more complex function. A function that's called with a date and time returns it in the format: Wednesday, 15 February, 2012, 10:00:00 AM<html> <head> <title>Functions</title> </head> <body> <?php function EnglishDateTime($date) { // Array with the English names of the days of the week $arrDay = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); // Array with the English names of the months $arrMonth = array("","January","February","March","April","May","June","July","August","September","October","November","December"); // The date is constructed $EnglishDateTime = $arrDay[(date("w",$date))] . ", " . date("d",$date); $EnglishDateTime = $EnglishDateTime . " " . $arrMonth[date("n",$date)] . " " . date("Y",$date); $EnglishDateTime = $EnglishDateTime . ", " . date("H",$date) . ":" . date("i",$date); return $EnglishDateTime; } // Test function echo EnglishDateTime(time()); ?> </body> </html>
The function above works on all web servers regardless of language. This means that you can use such a function if your website, for example, is hosted on a French server, but you want English dates.