🧩 Module 6: Functions
Objective: Learn how to create, call, and reuse functions in PHP to write cleaner,
modular, and more efficient code.
🔹 1. What Is a Function?
A function is a block of code that performs a specific task and can be reused anywhere in your script.
It allows you to write once, use many times — saving time and avoiding repetition.
<?php
function greetUser() {
echo "Welcome to StreetGeek Academy!";
}
greetUser(); // Call the function
?>
✅ Output:
Welcome to StreetGeek Academy!
🔹 2. Function Syntax
function functionName(parameters) {
// Code to be executed
return value; // (optional)
}
- Functions must start with the keyword
function - Names cannot start with a number
- Parentheses are required even if no parameters are passed
returnis optional but useful to send a value back
🧩 Example with Parameters
<?php
function greet($name) {
echo "Hello, $name!";
}
greet("Yogi"); // Output: Hello, Yogi!
greet("Brandon");
greet("Nicole");
?>
🔹 3. Functions That Return Values
Instead of echoing directly, functions can return values for flexible reuse.
<?php
function add($x, $y) {
return $x + $y;
}
$result = add(10, 5);
echo "Sum: $result";
?>
✅ Output:
Sum: 15
🧠 Tip: Always use return when you need to pass a value back to the caller.
🔹 4. Default Parameter Values
If a parameter isn’t provided, PHP can use a default value.
<?php
function greet($name = "StreetGeek") {
echo "Hello, $name!";
}
greet(); // Hello, StreetGeek!
greet("Yogi"); // Hello, Yogi!
?>
🔹 5. Variable Scope
The scope of a variable defines where it can be accessed.
| Type | Description |
|---|---|
| Local | Created inside a function; can only be used inside that function |
| Global | Declared outside; can be accessed inside using the global keyword |
| Static | Retains its value between function calls |
🧩 Example: Local vs Global
<?php
$city = "Richmond";
function showCity() {
global $city; // Access global variable
echo "We’re learning PHP in $city!";
}
showCity();
?>
✅ Output:
We’re learning PHP in Richmond!
🧩 Example: Static Variable
<?php
function counter() {
static $count = 0;
$count++;
echo "Count: $count<br>";
}
counter();
counter();
counter();
?>
✅ Output:
Count: 1
Count: 2
Count: 3
🧠 Without static, $count would reset to 0 each time.
🔹 6. Built-in String and Array Functions
PHP comes with hundreds of built-in functions. Here are a few essentials:
🔸 String Functions
| Function | Description | Example |
|---|---|---|
strlen() |
Get string length | strlen("StreetGeek") |
strtolower() |
Convert to lowercase | strtolower("YOGI") |
strtoupper() |
Convert to uppercase | strtoupper("academy") |
str_replace() |
Replace text | str_replace("Geek", "Guru", "StreetGeek") |
substr() |
Extract substring | substr("StreetGeek", 0, 6) |
🔸 Array Functions
| Function | Description | Example |
|---|---|---|
count() |
Count elements | count($colors) |
array_merge() |
Combine arrays | array_merge($a, $b) |
array_slice() |
Extract subset | array_slice($fruits, 1, 2) |
in_array() |
Check if value exists | in_array("Blue", $colors) |
🧩 Hands-On Practice
Exercise 1: Simple Greeting Function
Create greet.php:
<?php
function greet($name) {
echo "Hello, $name! Welcome to StreetGeek Academy.<br>";
}
greet("Yogi");
greet("Nicole");
greet("Brandon");
?>
✅ Output: Each name displays a personalized greeting.
Exercise 2: Addition Function
Create add.php:
<?php
function addNumbers($a, $b) {
return $a + $b;
}
echo "10 + 5 = " . addNumbers(10, 5);
?>
✅ Output:
10 + 5 = 15
Exercise 3: Default Parameter
Create welcome.php:
<?php
function welcome($name = "StreetGeek Student") {
echo "Welcome back, $name!<br>";
}
welcome(); // Uses default
welcome("Yogi"); // Custom name
?>
Exercise 4: Global and Local Scope
Create scope.php:
<?php
$academy = "StreetGeek";
function showAcademy() {
global $academy;
echo "You’re learning at $academy Academy.";
}
showAcademy();
?>
✅ Output:
You’re learning at StreetGeek Academy.
Exercise 5: Static Counter
Create count.php:
<?php
function increment() {
static $count = 0;
$count++;
echo "This function has been called $count times.<br>";
}
increment();
increment();
increment();
?>
✅ Output increments each call.
🎯 Mini Project – BMI Calculator
Goal: Build a function that calculates Body Mass Index and returns a health category.
Create bmi.php:
<?php
function calculateBMI($weight, $height) {
$bmi = $weight / ($height * $height);
return $bmi;
}
function getBMICategory($bmi) {
if ($bmi < 18.5) return "Underweight";
elseif ($bmi < 25) return "Normal";
elseif ($bmi < 30) return "Overweight";
else return "Obese";
}
$weight = 70; // kg
$height = 1.75; // meters
$bmi = calculateBMI($weight, $height);
echo "Your BMI is " . round($bmi, 1) . " - " . getBMICategory($bmi);
?>
✅ Output example:
Your BMI is 22.9 – Normal
🧠 Combines math, conditionals, and multiple functions into one working system.
🧾 Module 6 Quiz
| # | Question | Options | Correct |
|---|---|---|---|
| 1 | What keyword defines a function? | a) func · b) define · c) function | c |
| 2 | Which statement returns a value? | a) send · b) return · c) output | b |
| 3 | What keyword allows access to outside variables? | a) static · b) global · c) use | b |
| 4 | Which variable type retains its value across calls? | a) static · b) local · c) temporary | a |
| 5 | What will strlen("StreetGeek") return? |
a) 9 · b) 10 · c) 11 | c |
💪 Challenge Task – Dynamic Calculator
Objective: Create a PHP calculator using functions for add, subtract, multiply, and divide.
Create calculator.php and add these functions:
<?php
function add($a, $b) { return $a + $b; }
function subtract($a, $b) { return $a - $b; }
function multiply($a, $b) { return $a * $b; }
function divide($a, $b) {
return $b == 0 ? "Cannot divide by zero" : $a / $b;
}
$x = 10;
$y = 5;
echo "Add: " . add($x, $y) . "<br>";
echo "Subtract: " . subtract($x, $y) . "<br>";
echo "Multiply: " . multiply($x, $y) . "<br>";
echo "Divide: " . divide($x, $y);
?>
✅ Output:
Add: 15
Subtract: 5
Multiply: 50
Divide: 2
🧾 Submission Checklist
- ✅
greet.php→ personalized greetings - ✅
add.php→ returns correct math result - ✅
bmi.php→ functional BMI calculator - ✅
calculator.php→ function-based calculator - ✅ Quiz answers filled
🏁 Next Step: In Module 7, you’ll take everything you’ve learned and apply it to forms and user
input validation, learning to handle and protect user-submitted data — a crucial step toward secure web
development and building WordPress-like form workflows.