5. Functions (PHP)

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 prints
  • return → 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

ConceptMeaning
User-definedCustom functions created by user
ParametersInputs passed to function
Default argumentsPredefined values
Return valuesOutput from function
Variable functionsCall function using variable
Recursive functionsFunction calling itself

🧠 Practice Questions

Try these:

  1. Create a function to check even/odd
  2. Function to calculate square of a number
  3. Function with default argument (country = India)
  4. Return largest of two numbers
  5. Create a recursive function for sum of numbers (1 to n)
  6. Use variable function to call different math operations