In this chapter
We'll learn what a function is and why copy-pasted code drifts apart, how to declare a function, the difference between parameters and arguments, how return gives a value back — and why a function that echoes its result instead of returning it breaks every page that uses it.
The Problem in Real Life
Tuesday, 22 days before launch. Daniel Brooks booked a haircut with a hot towel for the bank-holiday Monday. Checkout charged him £30.25. The reminder text said £27.50, and so did his invoice. He writes to Olivia: "Which one is right?"
Marcus searches the code for the price calculation. It's in six files: book.php, checkout.php, reminder.php, invoice.php, admin.php and api.php — the same eight lines, copied and pasted. Last week someone added the 10% holiday surcharge. They found four of the copies.
"One calculation, one place," says Marcus. "That's a function." Mia writes her first one, calculatePrice(), and uses it in the invoice: $total = calculatePrice(2500, 250);. The page shows £27.50 at the very top, above the logo — and the invoice line itself says "Total: £".
The function prints the right price. So why is $total empty?
Mia
Six Copies vs. One Function
Copies drift apart
Six copies of the same code means six places to fix. Miss one, and the business has two prices.
Input and output
A function takes values in through its parameters and hands one value back with return.
Printing isn't returning
echo sends text to the page at once. return gives a value to the code that called the function.
Writing Functions
What a function is: a function is a named piece of code that you write once and call — run — as often as you like, from anywhere. You've used PHP's own functions since Act 01 (strlen(), count(), sprintf()) and seen small ones of your own since Act 02. This Act teaches them fully. This chapter covers the five basics:
- Why functions: one place for one job, so a fix reaches every page.
- Declaring:
function name(...) { ... }. - Parameters and arguments: the values a function takes in.
- Return values: the value a function gives back — and why that's different from printing it.
Why functions: copy-pasted code looks harmless on the day you paste it. Then the rules change — a holiday surcharge, a new add-on — and someone has to find every copy. BookBay had six and fixed four, so the same booking had two prices. A function puts the rule in one place, with a name; every page calls it, and a fix there is a fix everywhere. The principle has a name: DRY, "don't repeat yourself". Functions also make code easier to read, because calculatePrice(...) says what eight lines of arithmetic do.
<?php$basePence = 2500; // haircut$addOnPence = 250; // hot towel$isHoliday = true;// checkout.php — fixed last week$total = $basePence + $addOnPence;if ($isHoliday) {$total += intdiv($total * 10, 100); // 10% holiday surcharge}echo "Checkout: ", $total, "\n"; // Checkout: 3025// reminder.php — the copy nobody found$total = $basePence + $addOnPence;echo "Reminder: ", $total, "\n"; // Reminder: 2750
Declaring a function: you write function, a name, a pair of brackets with the parameters, and a block in curly braces: function calculatePrice(int $basePence, int $addOnPence): int { ... }. The int before each parameter and after the brackets are types; the next chapter covers them. Function names follow the same rules as variables, without the $, and by convention they're camelCase verbs that say what the function does: calculatePrice, formatPrice, sendReminder. Names are not case-sensitive (Act 02), but always call a function exactly as you declared it. In this course, money is always stored as whole pence in an int, as Act 04 recommended: £27.50 is 2750.
<?phpfunction calculatePrice(int $basePence, int $addOnPence): int{return $basePence + $addOnPence;}$haircut = calculatePrice(2500, 0);$withTowel = calculatePrice(2500, 250);echo $haircut, " ", $withTowel, "\n"; // 2500 2750echo calculatePrice(1000, 250), "\n"; // 1250: call it anywhere, as often as you like
Parameters and arguments: the variables in the declaration's brackets are parameters: $basePence and $addOnPence are placeholders. The values you pass when you call the function are arguments: in calculatePrice(2500, 250), 2500 goes into $basePence and 250 into $addOnPence, in order. Inside the function, parameters are ordinary local variables. Call a function with too few arguments, and PHP throws an ArgumentCountError. Extra arguments are simply ignored — another reason to keep the number of parameters small and obvious.
<?phpfunction calculatePrice(int $basePence, int $addOnPence): int // parameters{return $basePence + $addOnPence;}echo calculatePrice(2500, 250), "\n"; // arguments: 2500 and 250 → 2750try {calculatePrice(2500);} catch (ArgumentCountError $e) {echo $e->getMessage(), "\n";}// Too few arguments to function calculatePrice(), 1 passed in main.php on line 11 and exactly 2 expected
return: return $basePence + $addOnPence; ends the function and hands the value back to the line that called it, where it can be stored, printed or passed on: $total = calculatePrice(2500, 250);. A function can return one value, of any type; to give back several values, return an array and destructure it (Act 08): [$net, $surcharge] = priceParts(...). A function with no return — or with a bare return; — gives back null.
<?phpfunction priceParts(int $subtotalPence, bool $isHoliday): array{$surcharge = $isHoliday ? intdiv($subtotalPence * 10, 100) : 0;return [$subtotalPence, $surcharge];}[$subtotal, $surcharge] = priceParts(2750, true);echo "Subtotal $subtotal, surcharge $surcharge\n"; // Subtotal 2750, surcharge 275function nothingBack(){}var_dump(nothingBack()); // NULL
echo is not return: this was Mia's bug. Her function did echo "£" . number_format(...) and had no return. When the invoice called it, PHP printed the price right then — before the page had printed anything else, which is why it appeared above the logo — and then the function returned null. So $total was null, and "Total: £" had nothing to show. The rule: a function that calculates something returns it, and the code that shows things decides where to print it. A function that both calculates and prints can't be reused in a text message, an email or another calculation.
<?phpfunction formatPriceWrong(int $pence){echo "£" . number_format($pence / 100, 2); // prints NOW, returns null}function formatPrice(int $pence): string{return "£" . number_format($pence / 100, 2); // hands the text back}$line = "Total: " . formatPriceWrong(2750);echo "\n", $line, "\n";echo "Total: " . formatPrice(2750), "\n";// £27.50// Total:// Total: £27.50
Where to declare functions: you can call a function that is declared further down the same file: PHP reads all the top-level function declarations of a file before it runs the first line. Functions declared inside an if or inside another function only exist once that code has run, so don't do that. In a real project, functions live in their own file that every page includes (Act 13). The table below names every part of a function.
| Part | In function calculatePrice(int $basePence, int $addOnPence): int | Means |
|---|---|---|
| Name | calculatePrice | What you call it by; a verb in camelCase |
| Parameters | $basePence, $addOnPence | Local variables that receive the arguments |
| Parameter types | int, int | What each parameter accepts (chapter 2) |
| Return type | : int | What the function gives back (chapter 2) |
| Body | { ... } | The code that runs on each call |
| return | return $basePence + $addOnPence; | Ends the function and hands back the value |
| Arguments | calculatePrice(2500, 250) | The values passed in a call, in order |
<?phpecho formatPrice(3025), "\n"; // works: PHP reads the declarations firstfunction formatPrice(int $pence): string{return "£" . number_format($pence / 100, 2);}// £30.25
Key Takeaway
A function is named code you write once and call anywhere, so a fix in one place reaches every page (DRY). Declare it with function name(parameters) { ... }. Parameters are the placeholders; arguments are the values you pass, in order. return ends the function and hands one value back — echo only prints. A function that calculates should return its result and let the caller decide what to show.
Why This Matters
Prices, availability, reminders: a booking system has a handful of rules that many pages use. If each page has its own copy of a rule, the business has as many versions of the truth as it has pages. A function gives each rule exactly one home.
Returning instead of printing is what makes a function reusable: the same formatPrice() can fill an invoice, a text message, an email or an API response — because it only hands back the text and lets each caller decide what to do with it.
calculatePrice() returns the total, formatPrice() returns the text, and the invoice shows £27.50 in the right place. Mia replaces the copy in api.php — the code the mobile app calls — and the app shows Daniel's haircut for £0.27. The app sends prices in pounds, as 27.5, and the function expects pence. PHP didn't complain. That's the next chapter: parameter and return types.
