A function is a piece of code which takes one more input in the form of a parameter and does some processing and returns a value.
There are two parts which should be clear to you −
- Creating a PHP Function
- Calling a PHP Function
It’s very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you call it. Following example creates a function called writeMessage() and then calls it just after creating it. Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below −
<?php
/* Defining a PHP Function */
function writeMessage() {
echo “You are really a nice person, Have a nice time!”;
}
/* Calling a PHP Function */
writeMessage();
?>
Result −
You are really a nice person, Have a nice time!
PHP Functions with Parameters
PHP gives you the option to pass your parameters inside a function. You can pass as many parameters as you like. These parameters work like variables inside your function.
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo “Sum of the two numbers is : $sum”;
}
addFunction(10, 20);
?>
Result −
Sum of the two numbers is : 30