PHP functions are equivalent to other programming languages. A function is a part of code that takes one more input in the form of a parameter and does some processing and returns a value.
There are lots of functions like print_r(), fopen() and fread() etc. All these functions are built-in functions. In PHP, you can also create your own functions as well.
There are two factors that should be clear to you:
- Creating a PHP Function
- Calling a PHP Function
PHP User-Defined Functions
A function will be executed by a call to the function.
Syntax
function functionName() { code to be executed; }
PHP function approaches:
- Take the function name that recalls what the function does
- The function name can begin with a letter or underscore (not a number)
Example
function testMsg() { echo "Welcome to Oixiesoft!"; } testMsg(); // call the function
Output
PHP Functions with Parameters
To add extra functionality to a function, we can use parameters. A parameter is just like a variable. The function name is defined before the parameters. And the parameters are specified inside the parentheses ().
You can add multiple arguments and each argument is separated by a comma.
Example
function fruitName($fname) { echo " This is a $fname.<br>"; } fruitName("apple"); fruitName("kiwi"); fruitName("banana"); fruitName("mango");
Output
This is a kiwi.
This is a banana.
This is a mango
Example2: Multiple Parameters
function addFunction($num1, $num2) { $sum = $num1 + $num2; echo "Sum of the two numbers is : $sum"; } addFunction(15, 20);
Passing Arguments by Reference:
It is likely to pass arguments to functions by reference. It signifies that a reference to the variable is controlled by the function instead of a copy of the variable’s value.
Any modifications made to an argument in these circumstances will vary the value of the actual variable. You can pass an argument by reference by using an ampersand (&) to the variable name in either the function call or the function definition.
Example
function multiply_six(&$value) { $value *= 6; } $num = 3; multiply_six($num); echo $num;