Functions
Function
In PHP, a function is a reusable block of code that performs a specific task. Functions help you organize code, avoid repetition, and make programs easier to maintain.
types of functions:
- Built-in functions (already available in PHP)
built-in functions are pre-defined functions provided by PHP. You don’t need to create them—they are ready to use for common tasks like working with strings, arrays, numbers, files, and more.
- User-defined functions (created by the programmer)
A user-defined function is a function created by the programmer to perform a specific task. It helps reuse code, reduce repetition, and make programs easier to manage.
Create a Function
A user-defined function in PHP is created using the keyword function, followed by the function name. The code inside the function is written between curly braces { }, where { shows the start and } shows the end of the function.
Syntax
function functionName($parameter1, $parameter2) {
// code to be executed
return $value; // optional
}
Call a Function
To call a function in PHP, you write its name followed by parentheses (). A function is executed only when it is called.
Example
function greet($name) {
echo "Hello, $name!";
}
greet("Amit"); // function call
?>
Function Syntax Types
1. Function with Parameters
2. Function without Parameters
3. Function with Return Value
4. Function without Return Value
Example
// 1️⃣ Function with parameters (Parameterized Function)
function add($a, $b) {
echo $a + $b;
}
add(5, 10); // Output: 15
// 2️⃣ Function without parameters (Non-Parameterized Function)
function greet() {
echo "Hello!";
}
greet(); // Output: Hello!
// 3️⃣ Function with return value (Return Type Function)
function multiply($a, $b) {
return $a * $b;
}
echo multiply(4, 5); // Output: 20
// 4️⃣ Function without return value (Non-Return Type Function)
function showMessage() {
echo "Welcome to PHP!";
}
showMessage(); // Output: Welcome to PHP!
?>
Variable Number of Parameters
A variable number of parameters means a function can accept any number of arguments, instead of a fixed number. This is useful when we do not know in advance how many values will be passed to a function.
This type of function is also called a variadic function.
Syntax
function functionName(...$parameters) {
// code
}
Example
function sum(...$numbers) {
$total = 0;
foreach ($numbers as $num) {
$total += $num;
}
return $total;
}
echo sum(10, 20, 30);
?>