Back to results for “Functions & Scope”
PHP › Functions & Scope

How do you define and call a basic function in PHP, and what are function parameters and return values?

Beginner

Answer

You define a function in PHP using the function keyword followed by a name, a list of parameters the function accepts inside parentheses, and a body of code enclosed in curly braces, optionally using the return keyword to send a value back to whatever code called the function, letting you package up a reusable piece of logic that can be called by name whenever it is needed throughout your code.
function greet($name) {
    return "Hello, $name!";
}
echo greet('Ali');
Real-world example A pricing calculator defines a single reusable function that calculates tax on a given price, calling that same function consistently everywhere a tax calculation is needed rather than duplicating the calculation logic in multiple places.

Common follow-ups: What is the difference between a function that returns a value and one that does not?;Can a PHP function have multiple return statements?