A function is a reusable block of code that performs a specific task.
Using functions prevents code repetition, makes your scripts modular, and simplifies maintenance.
In programming, functions are broadly categorized into two main types based on who creates them:
Functions that you write yourself to handle specific logic unique to your application.
The purpose of a user-defined function is modularize code, avoid repetition, and solve custom problems.
Functions that are pre-packaged into the programming language itself. You can use them immediately without defining how they work internally.
The purpose of pre-packaged functions is to provide ready-to-use utility for common operations like string manipulation, math calculations, array handling, and file processing.
The syntax for a user-defined function is:
function name(arguments): returnType{
//Function code to be executed comes here
return value;//only when the function returns something
}
In modern PHP, you can indicate the data types of your arguments (the data to pass when the function is being used)
function sum(float $a, float $b): float{
return $a+$b;
}
A function could also have empty argument. This means no data is passed to the function when being used.
function welcome(): void{
echo "WELCOME TO PHP PROGRAMMING";
}
You can set default values for parameters. If no argument is provided when calling the function, the default value is used.
function introduce($name, $role = "Guest") {
echo "$name is logged in as a $role.
";
}
A function is called (used) by using the name and passing the arguments/parameters if the function takes one.
function sum(float $a, float $b): float{
return $a+$b;
}
echo sum(20,30);
function welcome(): void{
echo "WELCOME TO PHP PROGRAMMING";
}
echo welcome();
function introduce($name, $role = "Guest"): void {
echo "$name is logged in as a $role.
";
}
introduce("Godwin", "Admin"); // Output: Godwin is logged in as a Admin.
introduce("Mary"); // Output: Mary is logged in as a Guest.