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);
?>