Functions in PHP
By the end of this post you will be able to:
- Define what functions are
- Identify built-in functions
- Declare functions
- Identify functions and arguments
- Apply the return keyword
What are functions?
Sections of code that perform a specific task. Functions perform the same task as many times as required by the program. They perform routine tasks without the need to duplicate code.
PHP’s Built-in Functions
Similar to predefined variables PHP has a set of predefined functions. There are literally hundreds – here’s a search for strings: PHP Manual – Strings. In this post we will focus on: htmlspecialchars, is_numeric, sort — Sort an array.
htmlspecialchars is probably the most common of the in-built functions:
$name = $_GET['name']; //Without the function echo 'Welcome to our training session,' . $name . '! </br>'; //With the function echo 'Welcome to our training session, ' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '!'; /*htmlspecialchars($name, ENT_QUOTES, 'UTF-8') has three parameters: 1.) is the variable taken from the get statement 2.) is a built-in method in PHP to convert single or double quotes and other special characters into normal text objects 3.) The library required for character encoding */
Array functions
Another common resource for PHP defined functions are the array functions. Here is an example of a sort function.
$shakespearePlays = array("Hamlet", "Much Ado About Nothing", "Macbeth", "Comedy of Errors", "Loves Labors Lost", "Alls Well That Ends Well"); //This will by default sort in ascending order sort($shakespearePlays); //This will sort in reverse order //rsort //Good resource for sorting arrays: http://www.php.net/manual/en/function.sort.php foreach ($shakespearePlays as $key => $val) { echo "shakespeare plays [" . $key . "] = " . $val . "</br>"; } //Lets try counting the array //$shakespeareSonnets = array(); $result = count($shakespearePlays); if(!$result) { echo "There are no sonnets registered at the moment!"; } else { echo "There are $result records listed."; }
How do you build and declare functions?
- Firstly you need to write a function statement
- Then you need to ‘call’ the function
- Functions can either accept arguments or not
- Functions can return values back to the main program
- Functions can either work locally on one particular script or globally making them accessible to the whole application
Build your own functions
Rule of thumb: If your programme is performing a routine more than once and PHP has not already written a function for it – it is worth considering wrapping the logic in a function of your own.
Function syntax:
function functionName(){ code to be executed;}
Functions in action:
The function below does not return anything and has no arguments. They can simply be stand-alone entities.
function shakespeareQuotes() { echo "\"Love looks not with the eyes but with the mind.\" A Midsummer Night's Dream (I, i, 234)"; } shakespeareQuotes();
The example below is accepting one argument – you can use as many arguments as you want but I would advise to keep them to no more than say four arguments. Any more than that you would probably be better off using an array or using separate functions if the intention is to combine more than one piece of logic in a specific function.
//This function is designed to take an argument - in this case a material a chair is made of function chairFinish($material) { echo $material . " finish.
"; } echo "The chair is a "; chairFinish("Oak"); echo "The chair is a "; chairFinish("Mild steel"); echo "The chair is a "; chairFinish("Pine");
The third example is returning a value – note the return keyword.
//This function returns one value based on adding two arguments together function totalPrice($price,$delivery) { $total=$price+$delivery; return $total; } //The function is bieng called directly in the string that is being outputted to the user echo "Price of chair is: £100 + £16 delivery,Total: £" . totalPrice(100,16); //For more complex functions you can do this: $total = totalPrice(100,16); echo "Price of chair is: £100 + £16 delivery,Total: £" . $total;
What have we explored in this post?
We have:
- Define what functions are
- Identify built-in functions
- Declare functions
- Identify functions and arguments
- Apply the return keyword