PHP functions
A function is a segment of code grouped into a single entity. The great thing about functions is that you can re-use them. By doing so, you eliminate the need to re-type the same code over and over again. Once you implement a function, you can use its code by calling that function.
This tutorial focuses on:
- Creating functions
- Using parameters
- Calling functions
- Returning values
- PHP's built-in functions
Creating functions
To create a function, use the function keyword, followed by the function name, followed by parenthesis, followed by an opening brace and a closing brace. The lines of code which make up the function will go in between the braces.
In the above example, a function named printMessage is created that will print the text "Hello, this is a function."
Using parameters
Parameters are variables placed inside the parenthesis of a function which are used by the code inside the function in some way. Parameters are separated by commas.
In the above example, a function takes a value supplied by its name parameter and prints a message on a webpage.
Calling functions
Once you create a function, how do you actually use it? You have to call the function.
To call a function, refer to the function name and pass the appropriate parameter values to it (if the function has any parameters).
In the above example, a function named "subtract" is declared and it takes two values supplied by its $num1 and $num2 parameters. The code within the function specifies to print the result of subtracting the second number from the first.
Returning values
Functions can be used to return values. By doing so, the function simply acts as a value after its code has been executed. This way, a variable can take the value of a function which returns a value, or you can just print the value returned by the function.
To return a value from a function, the return keyword is used within the function.
10 + 10 = 20
In the above code, the function add() will return the value of the addition of its two parameters. Since this function returns a value, a variable can take its value. The variable $additionResult takes the value returned by the function when its two parameters are 2 and 4. The value of the variable $additionResult will therefore be 6 and it will be printed. The value returned by passing the parameters 10 and 10 to the add() function is also printed.
PHP's built-in functions
PHP has several built-in functions you can use for various purposes.
- abs() - Will return the absolute value of a number.
- max() - Returns the highest value from a set of specified numbers.
- strrev() - Will print a text string backwards.
- strtoupper() - Will print a text string in all uppercase letters.
20
.gnirts txet a si sihT
HERE IS SOME TEXT. THIS IS THE SECOND SENTENCE OF THE TEXT.