How to Define a Function in PHP
A function gives a name to a piece of work so you can run it with different values whenever you need it. In PHP you write one with the function keyword, list its parameters in brackets and hand back the result with return.
Syntax
function <name>($<parameter>, $<parameter>)
{
return <value>;
}
| Part | What it does |
|---|---|
function <name> | Declares the function and names it. |
($<parameter>, ...) | The values it receives; parameter names start with $. |
return <value> | Ends the call and hands the value back. |
The PHP manual: "A function is defined using the function keyword, a name, a list of parameters (which might be empty) separated by commas (,) enclosed in parentheses, followed by the body of the function enclosed in curly braces".
The Example
The example defines area, which multiplies a width by a height, and calls it for two rectangles.
Prerequisites
- PHP for the command line. This guide uses PHP 8.6.0.
Step 1: Write the Function
Create a file named main.php:

<?php
function area($width, $height)
{
return $width * $height;
}
echo area(3, 4), "\n";
echo area(10, 2), "\n";
Step 2: Run It
php main.php
12
20

One definition, two calls, two results. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Passing too few arguments, as in area(3) | Fatal error: Uncaught ArgumentCountError: Too few arguments to function area(), 1 passed … and exactly 2 expected | Pass every parameter, or give it a default value |
Misspelling the name, as in aera(3, 4) | Fatal error: Uncaught Error: Call to undefined function aera() | Check the spelling |
Forgetting return | The call gives null, which echo prints as nothing | Return the result |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
ArgumentCountError | The call passes fewer values than the function needs | Match the call to the parameters |
Call to undefined function | A typo, or the file that defines it isn't loaded | Fix the name, or require the file |
FAQ
Can a parameter have a default value?
Yes: function area($width, $height = 1) lets callers leave $height out.
Can I call a function before its definition in the file?
Yes, for functions defined at the top level of a file: PHP knows them before the file runs.
Conclusion
function name($a, $b) { return ...; } defines a function, and name(1, 2) calls it. Pass every parameter it needs, or give some default values.
Additional Resources
- User-defined functions, in the PHP manual.
