A function is a reusable block of code that performs a specific task. Instead of writing the same code many times, you write it once inside a function and then call that function whenever you need it.
What is a Function?
A function is like a recipe: you define the steps once, and whenever you need to follow that recipe, you just refer to it by name. In PHP, functions help you organize your code, make it shorter, and avoid errors.
Defining a Function in PHP
To create a function, use the function keyword followed by a name, parentheses, and curly braces. The code you want to run goes inside the braces.
function greet() {
echo "Hello, welcome to class!";
}
The function name should describe what it does. In PHP, function names are not case-sensitive, but it is good practice to use lowercase and underscores for readability.
Function Parameters
Parameters let you pass data into a function so it can work with different values. You list parameters inside the parentheses when defining the function.
function greetStudent($name) {
echo "Hello, " . $name . "!";
}
When you call this function, you provide an actual value (an argument) that replaces the parameter:
greetStudent("Amina"); // Output: Hello, Amina!
You can have multiple parameters:
function addNumbers($num1, $num2) {
$sum = $num1 + $num2;
echo $sum;
}
Return Values
A function can send back a result using the return keyword. When return is executed, the function stops running and sends the value back to wherever the function was called.
function multiply($a, $b) {
return $a * $b;
}
$result = multiply(5, 3);
echo $result; // Output: 15
Calling a Function
After you define a function, you use it by writing its name with parentheses. If the function needs parameters, you put the values inside the parentheses.
// Define the function
function calculatePrice($price, $quantity) {
return $price * $quantity;
}
// Call the function
$total = calculatePrice(1500, 4);
echo "Total: " . $total . " TSh"; // Output: Total: 6000 TSh
Worked Example
Consider a simple calculator that calculates the total cost of buying airtime. The function takes the price per unit and the number of units, then returns the total cost.
function calculateTotal($pricePerUnit, $units) {
$total = $pricePerUnit * $units;
return $total;
}
// Calculate cost for 5 units at 500 TSh each
$airtimeCost = calculateTotal(500, 5);
echo "You need to pay: " . $airtimeCost . " TSh";
Output:
You need to pay: 2500 TSh
This function can be reused any time you need to calculate a total — just call it with different values.
Real-life application
In Tanzania, small shop owners can use PHP functions to calculate profit from selling items. For example, a vendor at Mlimani City can write a function that takes the buying price and selling price of a bag of rice, then automatically calculates the profit for each sale, helping them track earnings quickly without doing the math manually every time.