What is a Function? (Function)
Function is a named block of code that you can call (execute) many times. Think of it as a reusable recipe.
Why use Functions?
- Reusability: Write once, call many times
- Readability: Organized, easy to understand
- Maintainability: Fix one place, affects everywhere
<?php
// Define a function
function sayHello() {
echo "Hello! Welcome to PHP Functions!";
}
// Call the function
sayHello(); // Output: Hello! Welcome to PHP Functions!
sayHello(); // Can call many times!
?>
Call 2: Hello! Welcome to PHP Functions!
User-defined Functions
You create your own function using the function keyword, followed by a name and { body }.
Syntax:
function functionName($param1, $param2) { // body }
<?php
// Calculate rectangle area
function calculateArea(float $width, float $height): float {
return $width * $height;
}
// Welcome message
function welcomeStudent(string $name, int $year): string {
return "Welcome $name! You are Year $year student.";
}
echo calculateArea(5, 3); // 15
echo welcomeStudent("Sokha", 2);
?>
Welcome Sokha! You are Year 2 student.
Built-in Functions (PHP has hundreds!)
PHP provides hundreds of ready-made functions. Just call them - no need to write them!
| # | Function | Description | Code | Output |
|---|---|---|---|---|
| 1 | strlen() | String length | strlen("Hello") | 5 |
| 2 | strtoupper() | Uppercase | strtoupper("php") | PHP |
| 3 | substr() | Substring | substr("Functions",0,4) | Func |
| 4 | explode() | Split string | explode(",","A,B,C") | A, B, C |
| 5 | implode() | Join array | implode("-",["X","Y"]) | X-Y-Z |
| 6 | count() | Count elements | count([10,20,30]) | 3 |
| 7 | array_sum() | Sum of array | array_sum([10,20,30]) | 60 |
| 8 | date() | Current date | date("Y-m-d") | 2026-02-28 |
Global Scope vs Local Scope
Local Scope: Variables created inside a function cannot be used outside.
Global Scope: Variables outside a function cannot be directly used inside a function.
To access global variables inside a function, use global keyword or $GLOBALS array.
<?php
$school = "ABC School"; // Global variable
function showLocal() {
$local = "I am local"; // Local variable
echo $local;
// echo $school; // ERROR! Cannot access global directly
}
// Method 1: global keyword
function showGlobal1() {
global $school;
echo "Method 1 (global): $school";
}
// Method 2: $GLOBALS
function showGlobal2() {
echo "Method 2 (\$GLOBALS): " . $GLOBALS['school'];
}
?>
Method 1 (global keyword): ABC School
Method 2 ($GLOBALS): ABC School
Warning: $local outside function = undefined (not accessible)
Parameters
You must pass values every time you call the function.
<?php
function addScores(int $math, int $science): int {
return $math + $science;
}
echo addScores(85, 90); // 175
?>
If you don't pass a value, the function uses the default value you defined.
<?php
function greet(string $name, string $greeting = "Hello"): string {
return "$greeting, $name!";
}
echo greet("Dara"); // Hello, Dara!
echo greet("Dara", "Good day"); // Good day, Dara!
?>
greet('Dara','Good day') = Good day, Dara!
Specify data types before parameters to prevent bugs: int $age, string $name, float $price
<?php
function calcDiscount(float $price, float $percent = 10.0): float {
return $price - ($price * $percent / 100);
}
echo calcDiscount(100.0); // 90 (default 10%)
echo calcDiscount(100.0, 25.0); // 75 (25% off)
?>
calcDiscount(100.0, 25.0) = 75 (25% off)
Return Values
return sends a value back from the function to the caller. You can return a single value or an array.
<?php
function getGrade(int $score): string {
if ($score >= 85) return "A";
if ($score >= 70) return "B";
if ($score >= 50) return "C";
return "F";
}
echo getGrade(92); // A
echo getGrade(65); // C
?>
getGrade(65) = C
getGrade(45) = F
<?php
function getStudentInfo(): array {
return [
'name' => 'Vuthy',
'age' => 20,
'grade' => 'A'
];
}
$student = getStudentInfo();
echo $student['name']; // Vuthy
?>
Passing by Reference
Pass by Value (default): Function receives a copy. Original variable does NOT change.
Pass by Reference (&): Function receives the actual address. Changes inside = changes outside!
Use & before parameter: function inc(&$x)
<?php
// Pass by Value - original does NOT change
function addTenValue(int $x): int {
$x += 10;
return $x;
}
// Pass by Reference - original DOES change
function addTenRef(int &$x): void {
$x += 10;
}
$num = 5;
$result = addTenValue($num);
echo "After by-value: \$num = $num"; // still 5
echo "Return value: $result"; // 15
$num2 = 5;
addTenRef($num2);
echo "After by-ref: \$num2 = $num2"; // now 15!
?>
By Reference: $num2 = 15 (changed to 15!)
Type Hinting (Parameter Types + Return Types)
Parameter type hints: Specify what type of data a function expects: int, float, string, array, bool
Return type: Specify what the function returns using : type after the parentheses.
void: Use : void when the function returns nothing.
About declare(strict_types=1):
By default, PHP will try to convert types automatically (e.g., "5" becomes 5). If you add declare(strict_types=1); at the very top of your file, PHP will throw a TypeError if the wrong type is passed. For beginners, it's optional but good practice!
<?php
// Parameter types + return type
function calcAvg(float $a, float $b, float $c): float {
return ($a + $b + $c) / 3;
}
function formatName(string $first, string $last): string {
return strtoupper($last) . ", " . $first;
}
function getScoreList(): array {
return [85, 92, 78, 95];
}
function printInfo(string $msg): void {
echo $msg; // void = returns nothing
}
echo calcAvg(80, 90, 70); // 80
echo formatName("Sokha", "Chan"); // CHAN, Sokha
?>
formatName('Sokha','Chan') = CHAN, Sokha
getScoreList() = [85, 92, 78, 95]
Anonymous Functions / Closures
Anonymous Function: A function without a name, often stored in a variable or passed to another function.
Closure: An anonymous function that can capture (use) variables from its parent scope with use ($var).
Common use cases: array_map(), array_filter(), usort()
<?php
// 1) Anonymous function in a variable
$double = function(int $n): int {
return $n * 2;
};
echo $double(5); // 10
// 2) array_map with anonymous function
$scores = [75, 82, 90, 68];
$bonused = array_map(function($s) { return $s + 5; }, $scores);
// [80, 87, 95, 73]
// 3) array_filter - keep scores >= 80
$high = array_filter($scores, function($s) { return $s >= 80; });
// [82, 90]
// 4) Closure with use() - capture external variable
$taxRate = 0.10;
$addTax = function(float $price) use ($taxRate): float {
return $price + ($price * $taxRate);
};
echo $addTax(100); // 110
?>
array_map (+5 bonus): [80, 87, 95, 73]
array_filter (>=80): [82, 90]
Closure use($taxRate=0.10): addTax(100) = 110
🎮 Interactive Demos
Demo 1: Function Playground (Calculator)
Enter two numbers and choose an operation. The result is computed using user-defined functions.
Demo 2: Scope Demo
Click "Run" to see how global vs local scope works in PHP.
Demo 3: Default Parameters
Enter a name. Leave greeting empty to use the default value ("Hello").
Demo 4: Type Hinting & Return Type
Choose a type and enter a value. For array, enter comma-separated values (e.g. "a,b,c").
Demo 5: Pass by Reference
Enter a number. See the difference between pass-by-value and pass-by-reference after adding 10.
Demo 6: Anonymous Function / Closure
Click "Run" to see array_map, array_filter, usort, and closure use() in action with student scores.
✍️ Practice Exercises (18 Questions)
A. Basic Functions + Return (6 questions)
P1. Write a function square($n) that returns $n * $n.
Hint: Use return $n * $n inside the function.
function square(int $n): int {
return $n * $n;
}
echo square(4); // 16
echo square(7); // 49
P2. Write a function isEven($n) that returns true if $n is even, false otherwise.
Hint: Use $n % 2 === 0.
function isEven(int $n): bool {
return $n % 2 === 0;
}
echo isEven(4) ? "true" : "false"; // true
echo isEven(7) ? "true" : "false"; // false
P3. Write a function maxOfThree($a, $b, $c) that returns the largest of three numbers.
Hint: Use max() built-in or compare with if statements.
function maxOfThree(int $a, int $b, int $c): int {
return max($a, $b, $c);
}
echo maxOfThree(10, 25, 18); // 25
P4. Write a function factorial($n) that returns the factorial of $n (e.g., 5! = 120).
Hint: Use a loop or recursion. factorial(0) = 1.
function factorial(int $n): int {
$result = 1;
for ($i = 2; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
echo factorial(5); // 120
echo factorial(0); // 1
P5. Write a function getMinMax(array $arr) that returns an array with 'min' and 'max' keys.
Hint: Use min() and max() built-in functions, return an associative array.
function getMinMax(array $arr): array {
return ['min' => min($arr), 'max' => max($arr)];
}
$result = getMinMax([5, 2, 9, 1, 7]);
echo "Min: " . $result['min']; // 1
echo "Max: " . $result['max']; // 9
P6. Write a function reverseString($str) that returns the reversed string without using strrev().
Hint: Use a for loop from end to start, or str_split + array_reverse + implode.
function reverseString(string $str): string {
$result = '';
for ($i = strlen($str) - 1; $i >= 0; $i--) {
$result .= $str[$i];
}
return $result;
}
echo reverseString("Hello"); // olleH
B. Scope + Globals (4 questions)
P7. A variable $color = "blue" is defined outside a function. Write a function that prints $color using the global keyword.
Hint: Add "global $color;" as the first line inside the function.
$color = "blue";
function showColor() {
global $color;
echo "Color is: $color";
}
showColor(); // Color is: blue
P8. Rewrite P7 using $GLOBALS instead of the global keyword.
Hint: Use $GLOBALS['color'] inside the function.
$color = "blue";
function showColorGlobals() {
echo "Color is: " . $GLOBALS['color'];
}
showColorGlobals(); // Color is: blue
P9. Create a global counter $count = 0, and a function incrementCounter() that uses global to increase $count by 1 each time it is called. Call it 3 times and print $count.
Hint: global $count; $count++;
$count = 0;
function incrementCounter() {
global $count;
$count++;
}
incrementCounter();
incrementCounter();
incrementCounter();
echo $count; // 3
P10. What is the output of this code? Explain why.
$x = 10;
function test() {
echo $x;
}
test();
Hint: Can a function access an outside variable without global?
Output: Warning: Undefined variable $x (or nothing in older PHP)
Why: $x is a global variable and cannot be accessed inside a function without using global $x; or $GLOBALS['x']. Functions have their own local scope.
C. Default Parameters + Type Hinting (4 questions)
P11. Write a function power(int $base, int $exp = 2): int that raises $base to $exp power. Default exponent is 2 (square).
Hint: Use a loop or ** operator. power(3) should return 9.
function power(int $base, int $exp = 2): int {
return $base ** $exp;
}
echo power(3); // 9 (3^2)
echo power(2, 5); // 32 (2^5)
P12. Write a function createTag(string $text, string $tag = "p"): string that wraps $text in an HTML tag.
Hint: return "<$tag>$text</$tag>".
function createTag(string $text, string $tag = "p"): string {
return "<$tag>$text$tag>";
}
echo createTag("Hello"); // Hello
echo createTag("Title", "h1"); // Title
P13. Write a function calcBMI(float $weight, float $height): float with return type float. BMI = weight / (height * height).
Hint: Weight in kg, height in meters. Return rounded to 1 decimal.
function calcBMI(float $weight, float $height): float {
return round($weight / ($height * $height), 1);
}
echo calcBMI(70, 1.75); // 22.9
P14. Write a function sumArray(array $numbers): int that takes an array of integers and returns their sum. Do NOT use array_sum().
Hint: Use a foreach loop and accumulate the total.
function sumArray(array $numbers): int {
$total = 0;
foreach ($numbers as $n) {
$total += $n;
}
return $total;
}
echo sumArray([10, 20, 30, 40]); // 100
D. Passing by Reference (2 questions)
P15. Write a function doubleIt(&$value) that doubles the value of a variable by reference. Demonstrate that the original variable changes.
Hint: $value *= 2; inside the function. No return needed.
function doubleIt(int &$value): void {
$value *= 2;
}
$num = 8;
echo "Before: $num\n"; // 8
doubleIt($num);
echo "After: $num\n"; // 16
P16. Write a function swapValues(&$a, &$b) that swaps two values by reference. After calling swapValues($x, $y), $x and $y should be exchanged.
Hint: Use a $temp variable to hold one value during the swap.
function swapValues(mixed &$a, mixed &$b): void {
$temp = $a;
$a = $b;
$b = $temp;
}
$x = "hello";
$y = "world";
swapValues($x, $y);
echo "$x, $y"; // world, hello
E. Anonymous Functions / Closures (2 questions)
P17. Given $numbers = [3, 1, 4, 1, 5, 9], use array_filter() with an anonymous function to keep only numbers greater than 3.
Hint: array_filter($numbers, function($n) { ... });
$numbers = [3, 1, 4, 1, 5, 9];
$filtered = array_filter($numbers, function($n) {
return $n > 3;
});
print_r($filtered);
// [4, 5, 9]
P18. Create a closure that takes a price and applies a tax rate captured with use($rate). The tax rate is $rate = 0.10 (10%). Calculate the final price (price + tax) for $50 and $120.
Hint: $calcTax = function($price) use ($rate) { ... };
$rate = 0.10;
$calcTax = function(float $price) use ($rate): float {
return $price + ($price * $rate);
};
echo $calcTax(50); // 55
echo $calcTax(120); // 132
🔑 Answer Key (Click to expand/collapse)
All 18 answers in one place
A. Basic Functions + Return (P1-P6)
P1. square($n)
function square(int $n): int { return $n * $n; }
echo square(4); // 16P2. isEven($n)
function isEven(int $n): bool { return $n % 2 === 0; }
echo isEven(4) ? "true" : "false"; // trueP3. maxOfThree($a, $b, $c)
function maxOfThree(int $a, int $b, int $c): int { return max($a, $b, $c); }
echo maxOfThree(10, 25, 18); // 25P4. factorial($n)
function factorial(int $n): int {
$result = 1;
for ($i = 2; $i <= $n; $i++) { $result *= $i; }
return $result;
}
echo factorial(5); // 120P5. getMinMax(array $arr)
function getMinMax(array $arr): array {
return ['min' => min($arr), 'max' => max($arr)];
}
$r = getMinMax([5,2,9,1,7]);
echo "Min:{$r['min']}, Max:{$r['max']}"; // Min:1, Max:9P6. reverseString($str)
function reverseString(string $str): string {
$result = '';
for ($i = strlen($str)-1; $i >= 0; $i--) { $result .= $str[$i]; }
return $result;
}
echo reverseString("Hello"); // olleHB. Scope + Globals (P7-P10)
P7. Use global keyword
$color = "blue";
function showColor() { global $color; echo "Color: $color"; }
showColor(); // Color: blueP8. Use $GLOBALS
$color = "blue";
function showColorG() { echo "Color: " . $GLOBALS['color']; }
showColorG(); // Color: blueP9. Global counter
$count = 0;
function inc() { global $count; $count++; }
inc(); inc(); inc();
echo $count; // 3P10. Scope quiz
Output: Warning (undefined variable). $x inside test() is not the same as global $x. Need global $x; to access it.
C. Default Params + Type Hinting (P11-P14)
P11. power($base, $exp=2)
function power(int $base, int $exp = 2): int { return $base ** $exp; }
echo power(3); // 9
echo power(2, 5); // 32P12. createTag($text, $tag="p")
function createTag(string $text, string $tag = "p"): string {
return "<$tag>$text$tag>";
}
echo createTag("Hello"); // <p>Hello</p>
echo createTag("Title", "h1"); // <h1>Title</h1>P13. calcBMI($weight, $height)
function calcBMI(float $w, float $h): float {
return round($w / ($h * $h), 1);
}
echo calcBMI(70, 1.75); // 22.9P14. sumArray(array $numbers)
function sumArray(array $numbers): int {
$total = 0;
foreach ($numbers as $n) { $total += $n; }
return $total;
}
echo sumArray([10, 20, 30, 40]); // 100D. Passing by Reference (P15-P16)
P15. doubleIt(&$value)
function doubleIt(int &$value): void { $value *= 2; }
$num = 8;
doubleIt($num);
echo $num; // 16P16. swapValues(&$a, &$b)
function swapValues(mixed &$a, mixed &$b): void {
$temp = $a; $a = $b; $b = $temp;
}
$x = "hello"; $y = "world";
swapValues($x, $y);
echo "$x, $y"; // world, helloE. Anonymous Functions / Closures (P17-P18)
P17. array_filter with anonymous function
$numbers = [3, 1, 4, 1, 5, 9];
$filtered = array_filter($numbers, function($n) { return $n > 3; });
print_r($filtered); // [4, 5, 9]P18. Closure with use($rate)
$rate = 0.10;
$calcTax = function(float $price) use ($rate): float {
return $price + ($price * $rate);
};
echo $calcTax(50); // 55
echo $calcTax(120); // 132