Advanced topics (anonymous functions, closures, arrow functions)

🔥 1. Anonymous Functions (Closures Basics)

👉 Anonymous functions = functions without a name

✅ Syntax:

$func = function() {
echo "Hello World";
};$func(); // call it

👉 You store the function in a variable and then call it.


✅ With Parameters:

$sum = function($a, $b) {
return $a + $b;
};echo $sum(5, 3);

📌 Where used in real life:

  • Callbacks
  • Array functions (array_map, array_filter)
  • Event handling

✅ Example with array:

$numbers = [1, 2, 3];$result = array_map(function($n) {
return $n * 2;
}, $numbers);print_r($result);

🔥 2. Closures (Very Important)

👉 A closure is an anonymous function that can access variables from outside using use.


❗ Problem (Without Closure)

$msg = "Hello";$func = function() {
echo $msg; // ❌ Error (undefined)
};

✅ Solution (Using use)

$msg = "Hello";$func = function() use ($msg) {
echo $msg;
};$func();

🔁 Pass by Reference in Closure

$count = 0;$increment = function() use (&$count) {
$count++;
};$increment();
$increment();echo $count; // 2

📌 Real Use Case:

  • Capturing environment variables
  • Middleware (Laravel, Express-like logic)
  • Custom callbacks

🔥 3. Arrow Functions (PHP 7.4+)

👉 Short syntax for writing functions


✅ Syntax:

$sum = fn($a, $b) => $a + $b;

✅ Example:

echo $sum(10, 5);

📌 Key Difference from Closure:

FeatureClosureArrow Function
SyntaxLongShort
use keywordRequiredNot needed
ScopeManualAutomatic

✅ Example with array:

$nums = [1, 2, 3];$result = array_map(fn($n) => $n * 3, $nums);print_r($result);

⚠️ Important Differences

🔸 Closure vs Arrow Function

👉 Closure:

$x = 5;$func = function() use ($x) {
return $x * 2;
};

👉 Arrow:

$x = 5;$func = fn() => $x * 2;

🔸 Limitation of Arrow Function

👉 Only single expression allowed

❌ Not allowed:

fn($x) => {
$y = $x * 2;
return $y;
};

💡 Real-World Examples


✅ 1. Filter Even Numbers

$nums = [1,2,3,4,5,6];$even = array_filter($nums, fn($n) => $n % 2 == 0);print_r($even);

✅ 2. Custom Sorting

$users = [
["name" => "A", "age" => 25],
["name" => "B", "age" => 20]
];usort($users, fn($a, $b) => $a['age'] <=> $b['age']);print_r($users);

✅ 3. Simple Middleware (Concept)

function middleware($next) {
return function($request) use ($next) {
echo "Before\n";
$next($request);
echo "After\n";
};
}

🧠 Interview-Level Insights

👉 Interviewers may ask:

❓ Why use closures?

  • Encapsulation
  • Cleaner callbacks
  • Avoid global variables

❓ Arrow vs Closure?

👉 Arrow:

  • Short
  • Automatic variable capture

👉 Closure:

  • More powerful
  • Supports multiple statements

❓ When NOT to use arrow functions?

  • When logic is complex
  • When multiple statements needed
  • When modifying external variables

🎯 Practice Questions

Try these:

  1. Use array_map with arrow function to square numbers
  2. Create closure that counts function calls
  3. Build a custom filter function
  4. Sort array of objects using closure
  5. Create a function that returns another function (closure)

PHP Functions – Interview Questions


🟢 Basic Level

1️⃣ What is a function in PHP?

👉 A function is a reusable block of code that performs a specific task.


2️⃣ How do you define a function in PHP?

function myFunction() {
echo "Hello";
}

3️⃣ What is the difference between echo and return?

👉 echo → outputs directly
👉 return → sends value back to caller


4️⃣ What are function parameters?

👉 Variables passed into a function as input.

function add($a, $b) {
return $a + $b;
}

5️⃣ What are default arguments?

👉 Predefined values used if no argument is passed.

function greet($name = "Guest") {
echo $name;
}

🟡 Intermediate Level


6️⃣ What is the difference between pass by value and pass by reference?

👉 Pass by value (default):

function test($x) {
$x = 10;
}

👉 Pass by reference:

function test(&$x) {
$x = 10;
}

📌 & allows modifying original variable


7️⃣ What are variable functions in PHP?

👉 Calling functions using a variable name.

function hello() {
echo "Hi";
}$f = "hello";
$f();

8️⃣ What is a recursive function?

👉 A function that calls itself.

function countDown($n) {
if ($n <= 0) return;
echo $n;
countDown($n - 1);
}

9️⃣ What are built-in functions?

👉 Predefined PHP functions like:

  • strlen()
  • count()
  • array_merge()

🔟 What is function overloading in PHP?

👉 PHP does NOT support traditional function overloading.

But you can simulate it using:

  • Default arguments
  • func_get_args()

🔴 Advanced Level


1️⃣1️⃣ What are anonymous functions (closures)?

👉 Functions without name.

$greet = function($name) {
return "Hello $name";
};echo $greet("Aditya");

1️⃣2️⃣ What is a closure in PHP?

👉 Anonymous function that can access variables from outside using use.

$message = "Hello";$func = function() use ($message) {
echo $message;
};$func();

1️⃣3️⃣ What are arrow functions in PHP?

👉 Short syntax (PHP 7.4+)

$sum = fn($a, $b) => $a + $b;

1️⃣4️⃣ What is callable in PHP?

👉 A type that represents valid function calls.

function run(callable $func) {
$func();
}

1️⃣5️⃣ What is function_exists()?

👉 Checks if function is defined.

if (function_exists('test')) {
test();
}

1️⃣6️⃣ What is include vs require in functions?

👉 include → warning if file missing
👉 require → fatal error (script stops)


1️⃣7️⃣ Can a function return multiple values?

👉 Yes (using arrays)

function getData() {
return [1, 2];
}

1️⃣8️⃣ What are variable scope types in functions?

👉 Types:

  • Local
  • Global
  • Static
function test() {
static $x = 0;
$x++;
echo $x;
}

1️⃣9️⃣ What is recursion base case?

👉 Condition to stop recursion.

if ($n == 0) return 1;

2️⃣0️⃣ What is the use of global keyword?

👉 Access global variables inside function.

$x = 10;function test() {
global $x;
echo $x;
}

🎯 Pro Interview Tips

👉 Interviewers often ask:

  • Difference between echo vs return
  • Pass by reference (&)
  • Closures & arrow functions
  • Recursion logic
  • Scope (global/static)

🚀 Bonus Coding Questions

Try solving:

  1. Write a function to reverse a string
  2. Create a function to find factorial (recursive)
  3. Function to check palindrome
  4. Pass array to function and return sum
  5. Create a closure example
  6. Dynamic calculator using variable functions

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

practice questions for PHP Loops

🟢 Basic Level

1️⃣ Print Numbers

Print numbers from 1 to 10 using:

  • for
  • while

2️⃣ Even Numbers

Print all even numbers from 1 to 20


3️⃣ Sum of Numbers

Find the sum of numbers from 1 to 100

👉 Output: 5050


4️⃣ Reverse Counting

Print numbers from 10 to 1


5️⃣ Multiplication Table

Print table of 5

👉 Output:

5 x 1 = 5
5 x 2 = 10
...

🟡 Intermediate Level

6️⃣ Factorial Program

Find factorial of a number
👉 Example: 5! = 120


7️⃣ Fibonacci Series

Print first 10 Fibonacci numbers

👉 Output:

0 1 1 2 3 5 8 ...

8️⃣ Count Digits

Input: 12345
Output: 5 digits


9️⃣ Reverse Number

Input: 1234
Output: 4321


🔟 Prime Number Check

Check whether a number is prime or not


🟠 Array + foreach Practice

1️⃣1️⃣ Print Array Values

$fruits = ["Apple", "Banana", "Mango"];

Print all values using foreach


1️⃣2️⃣ Find Largest Number

$numbers = [10, 25, 5, 40, 15];

Find the largest number


1️⃣3️⃣ Sum of Array

Find total sum of array elements


1️⃣4️⃣ Count Even Numbers in Array

Count how many even numbers are in array


🔴 Advanced Level

1️⃣5️⃣ Pattern Printing (Star)

*
**
***
****
*****

1️⃣6️⃣ Reverse Pattern

*****
****
***
**
*

1️⃣7️⃣ Skip Number using continue

Print 1 to 10 but skip 5


1️⃣8️⃣ Stop Loop using break

Print numbers until 7 comes, then stop


1️⃣9️⃣ Nested Loop (Table 1–5)

Print multiplication tables from 1 to 5


2️⃣0️⃣ Login Attempt System (Real Use)

Allow user 3 attempts to enter correct password
If correct → “Login Successful”
Else → “Account Locked”


💡 Pro Teaching Tip (For Your Students)

Start with:

  1. Numbers → Logic building
  2. Patterns → Loop mastery
  3. Arrays → Real-world usage
  4. Mini projects → Confidence

4. Loops (PHP)

Loops are used to repeat a block of code multiple times until a condition is met.


🔹 1. for Loop

Used when you know how many times you want to run the loop.

✅ Syntax:

for (initialization; condition; increment/decrement) {
// code
}

✅ Example:

for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}

🔍 Output:

1
2
3
4
5

👉 Best for: Counting loops


🔹 2. while Loop

Runs as long as the condition is true.

✅ Syntax:

while (condition) {
// code
}

✅ Example:

$i = 1;while ($i <= 5) {
echo $i . "<br>";
$i++;
}

👉 Best for: When number of iterations is unknown


🔹 3. do-while Loop

Executes the code at least once, even if the condition is false.

✅ Syntax:

do {
// code
} while (condition);

✅ Example:

$i = 1;do {
echo $i . "<br>";
$i++;
} while ($i <= 5);

👉 Key difference:

  • while → checks condition first
  • do-while → runs first, then checks

🔹 4. foreach Loop

Used to loop through arrays.

✅ Syntax:

foreach ($array as $value) {
// code
}

✅ Example:

$colors = ["Red", "Green", "Blue"];foreach ($colors as $color) {
echo $color . "<br>";
}

🔍 Output:

Red
Green
Blue

👉 With key & value:

$student = ["name" => "Aditya", "age" => 22];foreach ($student as $key => $value) {
echo $key . ": " . $value . "<br>";
}

🔹 5. break Statement

Used to stop the loop immediately.

✅ Example:

for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break;
}
echo $i . "<br>";
}

🔍 Output:

1 2 3 4

🔹 6. continue Statement

Skips the current iteration and moves to the next one.

✅ Example:

for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo $i . "<br>";
}

🔍 Output:

1 2 4 5

🧠 Quick Summary

Loop TypeUse Case
forFixed number of iterations
whileCondition-based looping
do-whileRun at least once
foreachArrays
breakStop loop
continueSkip iteration

Mini Project: Smart Login + Dashboard System

🎯 Features:

  • Login system
  • Form validation
  • Role-based dashboard
  • Status using ternary
  • Match (modern PHP)

📁 1. index.php (Login Form)

<form method="POST" action="login.php">
<h2>Login</h2>

<input type="text" name="username" placeholder="Enter Username"><br><br>
<input type="password" name="password" placeholder="Enter Password"><br><br>

<button type="submit">Login</button>
</form>

🔐 2. login.php (Validation + Login Logic)

<?php
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';// ✅ Form Validation (if-else)
if (empty($username) || empty($password)) {
echo "All fields are required ❗";
exit;
}// ✅ Dummy Users (Database simulation)
$users = [
"admin" => ["password" => "1234", "role" => "admin"],
"john" => ["password" => "1111", "role" => "user"],
"editor"=> ["password" => "2222", "role" => "editor"]
];// ✅ Login Check
if (isset($users[$username]) && $users[$username]['password'] === $password) {

$role = $users[$username]['role']; // ✅ Ternary (status message)
$status = ($role === "admin") ? "High Privilege User" : "Normal User"; echo "Login Successful ✅<br>";
echo "Status: $status <br>"; // Redirect to dashboard
header("refresh:2;url=dashboard.php?role=$role");} else {
echo "Invalid Credentials ❌";
}
?>

🧠 3. dashboard.php (Switch + Match)

<?php
$role = $_GET['role'] ?? 'guest';echo "<h2>Dashboard</h2>";// ✅ Switch Case (old method)
switch ($role) {
case "admin":
echo "Welcome Admin 👑<br>";
break;
case "editor":
echo "Welcome Editor ✍️<br>";
break;
case "user":
echo "Welcome User 👤<br>";
break;
default:
echo "Welcome Guest 🚫<br>";
}// ✅ Match Expression (modern PHP 8+)
$access = match($role) {
"admin" => "You have FULL access",
"editor" => "You can EDIT content",
"user" => "You can VIEW content",
default => "No Access",
};echo "<br>Access Level: $access";
?>

🧪 What Students Learn

✔ If-Else → form validation & login
✔ Ternary → quick status logic
✔ Switch → role-based UI
✔ Match → modern cleaner logic
✔ Real-world structure (multi-file project)


💡 Extra Improvements (Homework)

Ask students to:

  • Add logout button
  • Use sessions instead of GET
  • Add registration page
  • Store users in database (MySQL)

🎯 Teaching Tip

Run this project locally (XAMPP/WAMP):

http://localhost/project-folder/

MCQs for Exams

✅ Q1

Which statement is used for multiple conditions?

A) echo
B) if-else
C) print
D) break

👉 Answer: B


✅ Q2

What is the output?

$x = 10;
echo ($x > 5) ? "Yes" : "No";

A) No
B) Yes
C) Error
D) Nothing

👉 Answer: B


✅ Q3

Which is true about switch?

A) Uses strict comparison
B) Needs break
C) Returns value
D) Works only with numbers

👉 Answer: B


✅ Q4

Which feature belongs to match?

A) Requires break
B) Loose comparison
C) Returns value
D) Works only in PHP 5

👉 Answer: C


✅ Q5

What will this output?

$day = "Sunday";echo match($day) {
"Monday" => "Work",
"Sunday" => "Holiday",
};

A) Work
B) Holiday
C) Error
D) Nothing

👉 Answer: B


✅ Q6

Which operator is shorthand for if-else?

A) ==
B) ??
C) ?:
D) =>

👉 Answer: C

Practice Questions (Students)

🔹 Basic Level

  1. Check if a number is even or odd using if-else
  2. Check if a person is eligible to vote (18+)
  3. Find largest of 2 numbers

🔹 Intermediate Level

  1. Find grade based on marks
    • 90+ → A
    • 60–89 → B
    • Below 60 → Fail
  2. Create a simple calculator using switch:
    • +, -, *, /
  3. Check username & password (hardcoded)

🔹 Advanced Level

  1. Build login system with roles (admin/user/editor)
  2. Validate form:
    • Name required
    • Email valid
    • Password min 6 chars
  3. Convert switch to match expression
  4. Create traffic light system:
  • red → stop
  • yellow → wait
  • green → go

Real-world examples (login system, form validation)

Real-World Examples

🔐 A) Login System (If-Else + Ternary)

<?php
$username = "admin";
$password = "1234";$inputUser = "admin";
$inputPass = "1234";if ($inputUser === $username && $inputPass === $password) {
echo "Login Successful ✅";
} else {
echo "Invalid Credentials ❌";
}
?>

🔹 With Ternary (short version):

echo ($inputUser === $username && $inputPass === $password)
? "Login Successful ✅"
: "Invalid Credentials ❌";

📝 B) Form Validation (If-Else + Empty Check)

<?php
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';if (empty($name)) {
echo "Name is required ❗";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid Email ❗";
} else {
echo "Form Submitted Successfully ✅";
}
?>

🎯 C) Role-Based Access (Switch Case)

<?php
$role = "admin";switch ($role) {
case "admin":
echo "Full Access";
break;
case "editor":
echo "Edit Access";
break;
case "user":
echo "View Only";
break;
default:
echo "No Access";
}
?>

⚡ D) Modern Role System (Match – PHP 8+)

<?php
$role = "editor";$access = match($role) {
"admin" => "Full Access",
"editor" => "Edit Access",
"user" => "View Only",
default => "No Access",
};echo $access;
?>

3. Control Structures (PHP)

1️⃣ If, Else, Elseif

Used when you want to execute code based on conditions.

✅ Syntax:

if (condition) {
// code if condition is true
} elseif (another_condition) {
// code if second condition is true
} else {
// code if all conditions are false
}

✅ Example:

$marks = 75;if ($marks >= 90) {
echo "Grade A";
} elseif ($marks >= 60) {
echo "Grade B";
} else {
echo "Fail";
}

👉 Output: Grade B


2️⃣ Switch Case

Used when you have multiple possible values for a single variable.

✅ Syntax:

switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}

✅ Example:

$day = "Monday";switch ($day) {
case "Monday":
echo "Start of week";
break;
case "Friday":
echo "Weekend coming";
break;
default:
echo "Normal day";
}

👉 Output: Start of week


3️⃣ Ternary Operator

Short form of if-else.

✅ Syntax:

(condition) ? value_if_true : value_if_false;

✅ Example:

$age = 18;echo ($age >= 18) ? "Adult" : "Minor";

👉 Output: Adult

👉 Useful for short conditions only.


4️⃣ Match Expression (PHP 8+)

Modern alternative to switch, more powerful and safer.

🔥 Key Features:

  • No break needed
  • Strict comparison (===)
  • Returns a value
  • Cleaner syntax

✅ Syntax:

$result = match (variable) {
value1 => result1,
value2 => result2,
default => default_result,
};

✅ Example:

$day = "Monday";$message = match ($day) {
"Monday" => "Start of week",
"Friday" => "Weekend coming",
default => "Normal day",
};echo $message;

👉 Output: Start of week


⚡ Difference (Important for Students)

FeatureSwitch CaseMatch Expression
Break neededYesNo
ComparisonLoose (==)Strict (===)
Returns valueNoYes
SyntaxLongerCleaner

💡 When to Use What?

  • if-else → Complex conditions (ranges, multiple checks)
  • switch → Many fixed values (old method)
  • ternary → Short conditions (one line)
  • match → Best modern choice (PHP 8+)