How to Create and Use Functions in PHP (With Examples for Beginners)
In PHP, a function is a block of code that is executed to perform a specific task.
This is a good approach to avoid code repetition.
You can call a PHP function at any time you need it.
Define a Function
To define a function, we give it a name and the code to execute:
function sayHello() {
echo "Hello, welcome to our website!";
}
Call a Function
To call a function, we use the name followed by the parentheses:
sayHello(); //Hello, welcome to our website!
Functions with Parameters
In PHP, a function can take parameters:
function sayHello($name) {
echo "Hello, $name welcome to our website!";
}
sayHello("sam"); //Hello, sam welcome to our website!
Return Values from Functions
You can use the return keyword to return data from a function:
function calc($a,$b) {
return $a * $b;
}
$result = calc(5,8);
echo $result; // 40
Multiple Parameters
In PHP, a function can take multiple parameters:
function getUser($firstName,$lastName) {
return $firstName . " " . $lastName;
}
echo getUser("John","Doe"); // John Doe