Skip to main content

How to Define a Function in PHP

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
function <name>($<parameter>, $<parameter>)
{
return <value>;
}
PartWhat 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:

main.php, which defines function area($width, $height) returning width times height, and echoes area(3, 4) and area(10, 2).

main.php
<?php

function area($width, $height)
{
return $width * $height;
}

echo area(3, 4), "\n";
echo area(10, 2), "\n";

Step 2: Run It​

Terminal
php main.php
Output
12
20

A zsh terminal where php main.php prints 12 and 20.

One definition, two calls, two results. The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo 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 expectedPass 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 returnThe call gives null, which echo prints as nothingReturn the result

Troubleshooting​

SymptomLikely causeFix
ArgumentCountErrorThe call passes fewer values than the function needsMatch the call to the parameters
Call to undefined functionA typo, or the file that defines it isn't loadedFix 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​