Functions are reusable blocks of code that perform a specific task.
👉 Instead of writing the same code again and again, you define a function and call it when needed.
1️⃣ User-defined Functions
These are functions created by you using the function keyword.
✅ Syntax:
function functionName() {
// code
}
✅ Example:
function sayHello() {
echo "Hello World!";
}sayHello(); // calling function
👉 Output:
Hello World!
2️⃣ Function Parameters
Parameters are inputs passed to a function.
✅ Example:
function greet($name) {
echo "Hello $name";
}greet("Aditya");
👉 Output:
Hello Aditya
👉 You can pass multiple parameters:
function add($a, $b) {
echo $a + $b;
}add(5, 3);
3️⃣ Default Arguments
You can assign default values to parameters.
👉 If no value is passed, the default is used.
✅ Example:
function greet($name = "Guest") {
echo "Hello $name";
}greet(); // uses default
greet("Aditya");
👉 Output:
Hello Guest
Hello Aditya
4️⃣ Return Values
Functions can return values using return.
👉 This is very important for real applications.
✅ Example:
function add($a, $b) {
return $a + $b;
}$result = add(10, 5);
echo $result;
👉 Output:
15
👉 Difference:
echo→ directly printsreturn→ sends value back
5️⃣ Variable Functions
In PHP, you can call a function using a variable name.
👉 Function name stored in a variable.
✅ Example:
function sayHi() {
echo "Hi!";
}$func = "sayHi";
$func(); // calls sayHi()
👉 Output:
Hi!
👉 Useful in:
- Dynamic function calls
- Callback systems
6️⃣ Recursive Functions
A function that calls itself is called a recursive function.
👉 Used for:
- Factorial
- Tree structures
- File systems
✅ Example: Factorial
function factorial($n) {
if ($n == 0) {
return 1;
}
return $n * factorial($n - 1);
}echo factorial(5);
👉 Output:
120
👉 Flow:
5 × 4 × 3 × 2 × 1
⚠️ Important:
Always define a base condition, otherwise infinite loop will occur.
🎯 Summary
| Concept | Meaning |
|---|---|
| User-defined | Custom functions created by user |
| Parameters | Inputs passed to function |
| Default arguments | Predefined values |
| Return values | Output from function |
| Variable functions | Call function using variable |
| Recursive functions | Function calling itself |
🧠 Practice Questions
Try these:
- Create a function to check even/odd
- Function to calculate square of a number
- Function with default argument (country = India)
- Return largest of two numbers
- Create a recursive function for sum of numbers (1 to n)
- Use variable function to call different math operations






