Sherif's Tech Blog

Just another guy on the Internet with a keyboard…

PHP Functions

Using and Defining Functions in PHP

A function is basically a way to write code that will only be executed at the time your code calls it. It offers multiple benefits such as code re-usability. This means you can write some code that may be executed multiple times throughout various parts of your script. We explained language constructs in the previous tutorial that showed us how to control the code, but functions offer a different kind of control. We explained that in PHP, statements are executed in the same order they are presented and control structures like the if/elseif/else control structure allow us to determine which statements may get executed given a set of conditions or the evaluation of a set of expressions such as in the for loop. A function makes it possible to separate code logic from execution. There are two kinds of functions in PHP. There are built-in functions that PHP already defines for us and allows us to call them anywhere in our code and there are user-defined functions that you may define yourself and call anywhere they are defined in your code.

Functions take on what are referred to as parameters or arguments. A function may take one or more, or no parameters in the form of expressions separated by commas and enclosed in parenthesis after the function name. If the function is defined then putting the function name, followed by parenthesis with the parameters inside the parenthesis (if there are any) in a statement calls on the function to execute its defined code and returns its value to that expression (if it returns one). Functions are also case-insensitive in PHP.

Built In Functions

We’ll take a look at how to use some of PHP’s built-in functions first. Some simple built in functions you may want to explore first are functions that do things with the different data types we discussed earlier in this tutorial. You may want to change the case of a string, for example. You may want to reverse the order of characters in a string. These are classified in the documentation under String Functions. You may want to work with arrays. These are classified in the documentation as Array Functions. Lets take a look at some basic functions PHP offers and what they do. The output of each function is included in the examples below in comments (comments are highlighted in green by the syntax highlighter in these examples).

echo strtoupper('php is awesome!');

/*
* OUTPUT:
* PHP IS AWESOME
*/

echo strtolower('PHP IS AWESOME!');

/*
* OUTPUT:
* php is awesome!
*/

$string = strrev('php is awesome!');
echo $string;
echo strtoupper($string);
echo strtoupper(strrev('php is awesome!'));

/*
* OUTPUT:
* !emosewa si php
* !EMOSEWA SI PHP
* !EMOSEWA SI PHP
*/

Notice that in the first examples of strtoupper() and strtolower() I called on the function inside of the echo construct. The return value of those functions will then be sent to the construct and it will output them. The next example demonstrates how you can assign a variable with the return value of a function. We assigned $string with the call to strrev(), which then returns the result and assigns it to that variable. We then output the string using echo. Then I call on a function inside the echo construct using the string as the parameter of that function (which is already the reversed string). strtoupper() then takes that parameter and returns the result to echo, which outputs the uppercase version of the same string. Note, the string itself will not change. The return value of the function is separate from the value of the string so they do not directly affect one another. Then I demonstrated how you can call a function from within another function. What happens in the last part is that I call strrev() with a string parameter and it then returns the value of the reversed string to strtoupper(). strtoupper() then takes the return value of strrev() and returns that string in uppercase to echo. Finally we get the same output as the previous statement.

User Defined Functions

PHP also allows you to define your own functions. While it is possible to call another function from within a function definition it is important to keep in mind that in PHP all function definitions reside on the global scope. This basically means you don’t want to define a function inside of another function definition even though PHP won’t stop you from doing so. We’ll discuss scope in more detail in the next section, but for now this should be a general rule of thumb.

The first concept you should grasp when creating your own functions is learning how to keep the function definition separate from what you will end up doing with that function, or how it will be used. Think of the function definition as a way to tell PHP here is what I want you to do if I should happen to call on this function. PHP will store the function definition in memory, but it won’t ever execute that function until you explicitly call it. Calling the function strtoupper(), for example, was demonstrated in the example above. Simply by putting the function name, followed by parenthesis, in an expression we are calling on the function to be executed. It is also possible in PHP for a function to call on itself (this is called recursion), but for now we’ll just keep in this in mind as a side-note.

The function definition starts with the keyword function, followed by white space, followed by the function name, followed by parenthesis. Inside of the parenthesis you may declare any variables you would like to use as function parameters. PHP does not support or require declaring the variable type, but there are two exceptions. The parameter may be declared as either array or class type in the parameter definition, but nothing else. Next we begin the function defined code inside of curly braces, remember this is how you group statements in PHP and a function definition is made up of a group of statements.

/*
* This defines the function average
*/
function average($x, $y, $z) {
    $sum = $x + $y + $z;
    $average = $sum / 3;
    return $average;
}

/*
* This uses the function average
*/
echo "The average of 1, 2, and 3 is: " . average(1,2,3) . "\nThe average of 4, 5, and 6 is: " . average(4,5,6);

/*
* OUTPUT:
* The average of 1, 2, and 3 is: 2
* The average of 4, 5, and 6 is: 5
*/

The obvious benefit from this code is that we can now call on the function average multiple times throughout our script and it will execute the same code and return the desired result. The other way we could have done it to achieve the same result would be to put the code directly into the echo construct as two expressions, but then we are basically writing the same exact code twice with different sets of expressions. If we decide to later change the code to calculate the average of 4 integers instead of 3 we would then have to go back and change the code in both places in the echo construct. Doesn’t seem like too much trouble when the function is this short and you’re only using it twice, but when you are using the same code in dozens, hundreds, or even thousands of places throughout your code this save you a lot of unnecessary headache.

* IMPORTANT NOTE: function is a reserved keyword in PHP, along with many other reserved keywords. It cannot be used as a function name. So, PHP won’t allow you to declare a function name using the name function. Please check the list of PHP reserved words in the documentation to see what other reserved words can’t be used as function names. Also, it is important to note that PHP does not allow you to redeclare a function. This means you can not define any function more than once in the same script. This includes any built-in functions already defined by PHP core or any of its loaded extensions.

Your email address will not be published. Required fields are marked *

*