🐘 PHP Functions (Beginner)

Functions · Scope · Parameters · Return · Reference · Type Hinting · Anonymous Functions

📌 Instructions

1

What is a Function? (Function)

Concept

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
Code
<?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! ?>
Output
Call 1: Hello! Welcome to PHP Functions!
Call 2: Hello! Welcome to PHP Functions!
2

User-defined Functions

Concept

You create your own function using the function keyword, followed by a name and { body }.

Syntax:

function functionName($param1, $param2) { // body }
Code
<?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); ?>
Output
calculateArea(5, 3) = 15
Welcome Sokha! You are Year 2 student.
3

Built-in Functions (PHP has hundreds!)

Concept

PHP provides hundreds of ready-made functions. Just call them - no need to write them!

Code + Output
# Function Description Code Output
1strlen()String lengthstrlen("Hello")5
2strtoupper()Uppercasestrtoupper("php")PHP
3substr()Substringsubstr("Functions",0,4)Func
4explode()Split stringexplode(",","A,B,C")A, B, C
5implode()Join arrayimplode("-",["X","Y"])X-Y-Z
6count()Count elementscount([10,20,30])3
7array_sum()Sum of arrayarray_sum([10,20,30])60
8date()Current datedate("Y-m-d")2026-02-28
4

Global Scope vs Local Scope

Concept

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.

Code
<?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']; } ?>
Output
Local inside function: I am local variable
Method 1 (global keyword): ABC School
Method 2 ($GLOBALS): ABC School
Warning: $local outside function = undefined (not accessible)
5

Parameters

5A - Normal 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 ?>
addScores(85, 90) = 175
5B - Default Parameters

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') = Hello, Dara!
greet('Dara','Good day') = Good day, Dara!
5C - Type Hints on Parameters

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) = 90 (default 10%)
calcDiscount(100.0, 25.0) = 75 (25% off)
6

Return Values

Concept

return sends a value back from the function to the caller. You can return a single value or an array.

Return Single Value
<?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(92) = A
getGrade(65) = C
getGrade(45) = F
Return Array
<?php function getStudentInfo(): array { return [ 'name' => 'Vuthy', 'age' => 20, 'grade' => 'A' ]; } $student = getStudentInfo(); echo $student['name']; // Vuthy ?>
Student: name=Vuthy, age=20, grade=A
7

Passing by Reference

Concept

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)

Code
<?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! ?>
Output
By Value: $num = 5 (unchanged), return = 15
By Reference: $num2 = 15 (changed to 15!)
8

Type Hinting (Parameter Types + Return Types)

Concept

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!

Code
<?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 ?>
Output
calcAvg(80,90,70) = 80
formatName('Sokha','Chan') = CHAN, Sokha
getScoreList() = [85, 92, 78, 95]
9

Anonymous Functions / Closures

Concept

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()

Code
<?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 ?>
Output
$double(5) = 10
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.

P2. Write a function isEven($n) that returns true if $n is even, false otherwise.

Hint: Use $n % 2 === 0.

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.

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.

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.

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.

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.

P8. Rewrite P7 using $GLOBALS instead of the global keyword.

Hint: Use $GLOBALS['color'] inside the function.

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++;

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?

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.

P12. Write a function createTag(string $text, string $tag = "p"): string that wraps $text in an HTML tag.

Hint: return "<$tag>$text</$tag>".

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.

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.

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.

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.

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) { ... });

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) { ... };

🔑 Answer Key (Click to expand/collapse)

All 18 answers in one place