Why functions
As programs grow, the same steps appear again and again: format a price, calculate tax, check an email address. Copying the code each time means fixing the same bug in many places. A function packages those steps under a name, so you write them once and call them wherever you need them.
You have used many built-in functions already: strlen(), round(), count(). Now you will write your own.
Defining and calling a function
A function definition starts with the keyword function, then a name, brackets for the parameters, and a body in braces:
<?php
function greet()
{
echo "Welcome to the shop!\n";
}
greet();
greet();Welcome to the shop!
Welcome to the shop!Defining the function does nothing by itself. The code inside runs only when the function is called, with its name followed by brackets. Function names follow the same rules as variable names, without the $, and they are not case-sensitive; still, always call a function exactly as it is written. The usual style is camelCase verbs that say what the function does: calculateTax, sendInvoice, formatPrice.
Parameters and arguments
Most functions need input. Parameters are variables listed in the brackets of the definition; the values you pass when calling are the arguments:
<?php
function greetCustomer($name, $city)
{
echo "Hello $name from $city!\n";
}
greetCustomer("Asha", "Delhi");
greetCustomer("Liam", "Dublin");Hello Asha from Delhi!
Hello Liam from Dublin!Arguments are matched to parameters by position: the first argument goes into $name, the second into $city. Calling it with too few arguments is an error. Defaults, named arguments and types come in the next lesson.
Returning a value
Printing from inside a function is limiting: the caller cannot use the result. Usually a function should return its result and let the caller decide what to do with it:
<?php
function priceWithTax($price, $rate)
{
return round($price * (1 + $rate), 2);
}
$keyboard = priceWithTax(89.5, 0.18);
$mug = priceWithTax(18.75, 0.18);
echo "Keyboard: $keyboard\n";
echo "Mug: $mug\n";
echo "Both: " . ($keyboard + $mug) . "\n";Keyboard: 105.61
Mug: 22.13
Both: 127.74return does two things: it hands a value back, and it ends the function at once. Code after a return in the same path never runs, which is why the early-return style from if, elseif and else works:
<?php
function stockLabel($units)
{
if ($units === 0) {
return "Sold out";
}
if ($units < 10) {
return "Only $units left";
}
return "In stock";
}
echo stockLabel(0) . "\n";
echo stockLabel(4) . "\n";
echo stockLabel(60) . "\n";Sold out
Only 4 left
In stockA function that reaches its end without return gives null. To return several values at once, return an array and unpack it:
<?php
function splitName($fullName)
{
$parts = explode(" ", $fullName, 2);
return [$parts[0], $parts[1] ?? ""];
}
[$first, $last] = splitName("Kavya Nair");
echo "First: $first, last: $last\n";First: Kavya, last: NairOrder of definition
PHP reads the whole file before running it, so a top-level function can be called above the place where it is defined:
<?php
echo double(21) . "\n";
function double($n)
{
return $n * 2;
}42The exception is a function defined inside an if or another function: it exists only once that code has run. Defining the same function name twice is a fatal error, which you will meet when the same file is included twice; include and require shows how to avoid that.
Built-in functions
PHP comes with thousands of functions, grouped by topic in the PHP manual: strings, arrays, maths, dates, files, JSON and more. Before writing a function, check whether PHP already has one. function_exists() tells you whether a name is defined:
<?php
var_dump(function_exists('str_contains'));
var_dump(function_exists('priceWithTax'));
echo ucwords("mechanical keyboard") . "\n";
echo str_repeat("=", 10) . "\n";bool(true)
bool(false)
Mechanical Keyboard
==========The manual page for each function shows its parameters, return value, examples and the version in which it was added. Reading it is a skill worth building early.
Good functions
A few habits make functions pleasant to use:
- One job each.
calculateTotal()should calculate; printing belongs elsewhere. - Return, do not echo, unless the function's job is output.
- Clear names that start with a verb.
- Few parameters. More than three or four is a sign the function does too much, or that the values belong together in an array or object.
Common mistakes
- Forgetting the brackets when calling:
greet;does nothing useful. - Echoing instead of returning, so the result cannot be stored or reused.
- Using a variable from outside the function inside it. Functions have their own scope, explained in Variable scope, global and static. Pass values as arguments.
- Expecting code after return to run.
Exercise
Write a function cartTotal($prices) that takes an array of prices and returns the total, adding 49 shipping when the total is under 500. Print the result for [89.5, 18.75] and for [199.99, 89.5, 250].
Show one possible answer
<?php
function cartTotal($prices)
{
$total = array_sum($prices);
if ($total < 500) {
$total += 49;
}
return $total;
}
echo cartTotal([89.5, 18.75]) . "\n";
echo cartTotal([199.99, 89.5, 250]) . "\n";157.25
539.49array_sum() is a built-in function that adds every value in an array.
Key points
- A function is a named block of code that can take arguments and return a value.
- return sends a value back and ends the function immediately. A function with no return gives null.
- Functions can be called before they are defined in the same file.
- PHP ships with thousands of built-in functions; check the manual before writing your own.