Hopefully you are pretty secure with the basics of PHP by now. If not, you should read part 1 and part 2 of this series. This part is about functions. What are they; how do you use them; and how can you utilise your own functions? Functions can be a great tool to speed up your coding and to make applications run much more smoothly, so let’s go!

What are functions?

Functions are blocks of code that can be called upon at any point in the script to perform a particular task or ‘function’. There are more than 750 functions built into a normal install of PHP, but you can define your own too, making them very versatile and easy.

How do I use functions?

You use functions by calling them from within your code, this can be done anywhere in the script, and for built-in functions, it does not require any extra code or a file to be included.

One useful function which is built in is strlen, this returns the length of the string which you input, for example:

<?php
$length = strlen("MattyBatty"); //This sets the value of $length to the strlen of 'MattyBatty'
echo $length; //This would echo '10'
?>

The “MattyBatty” part is what we call an argument, this is a variable which is passed to a function which allows it to perform a different task or have a different output depending on what is put in.

The Best Bit

Probably the best bit about functions is the ability to write your own. This means that instead of writing the same piece of code over and over again to use with different strings, you can write a function and have the string as the argument. A common use for functions is for mathematical calculations. For example, you could create the function add(), or multiply() like this.

<?php
function multiply($num1, $num2) //Defines the function and the argument names.
   {
   return $num1*$num2; //Multiplies the two numbers and returns the result.
   }
?>

Explained – First, we define the function using the word ‘function’. This tells PHP we are about to write a function. We then give the function a name, in this case, ‘multiply’. Next, we give the arguments names, separated by commas. This is so when someone calls the function like this:

<?php
echo multiply(3,4);
?>

$num1 becomes 3 and $num2 becomes 4. We then enclose the actual ‘task’ in curly brackets { }. Inside these we use the word return so that the function returns the answer to the code that called it, ready to be echo’d or used in a different function.

Of course, functions can be much more complex than that. I was just giving you a taster into the world of PHP functions. I hope you have enjoyed my short series of tutorials and I hope you now understand PHP a little better. Thank you for reading my series, and make sure you check out the other two as well. You never know, you might learn something new!