PHP Functions for Beginners: A Simple Guide
Learn PHP functions for beginners: what they are, how to define, call, and return values from them, with simple copy-pasteable code examples.
Learn PHP functions for beginners: what they are, how to define, call, and return values from them, with simple copy-pasteable code examples.
A PHP function is a named, reusable block of code that performs one task. Instead of writing the same lines of code over and over, you write them once inside a function, give the function a name, and then "call" that name whenever you need the task done. This guide shows you exactly how to write, call, and use PHP functions, with small examples you can copy, paste, and run right away.
If you have never written a PHP function before, don't worry. We will start from the very basics: how a function is shaped, how to pass information into it, how to get information back out of it, and a few common mistakes to avoid. No prior programming knowledge is assumed.
Think of a function like a small machine. You give it some ingredients (called parameters), it does some work, and it can hand you back a result (called a return value). You build the machine once, then use it as many times as you like.
In code terms, a function is a block of PHP statements grouped together under one name using the keyword function. Once defined, you "call" the function by writing its name followed by parentheses, for example greet().
Here is the smallest possible PHP function: one that prints a greeting message.
<?php
function sayHello() {
echo "Hello, welcome to PHP!";
}
sayHello();Line by line: function is the keyword that tells PHP "I am creating a function." sayHello is the name we chose for it (you can name it almost anything, as long as it starts with a letter or underscore). The parentheses () come right after the name, even when the function does not need any input. Everything between the curly braces { } is the function's body — the code that runs when the function is called. The last line, sayHello();, is the function call. Notice that when you define a function you write { }, but when you call it you write ( ); with a semicolon and no curly braces.
Most functions need some input to work with. A parameter is a placeholder variable listed inside the parentheses when you define the function. An argument is the actual value you pass in when you call it.
<?php
function sayHelloTo($name) {
echo "Hello, $name!";
}
sayHelloTo("Maria");
sayHelloTo("Ahmed");$name is the parameter — a variable that only exists inside this function, waiting to be filled in. When we call sayHelloTo("Maria"), the text "Maria" is the argument, and it gets copied into $name for that run of the function. Call the same function again with a different argument, "Ahmed", and you get a different result. This is the whole point of parameters: the same function can behave differently depending on what you feed it.
You can also add more than one parameter, separated by commas:
<?php
function sayHelloFullName($firstName, $lastName) {
echo "Hello, $firstName $lastName!";
}
sayHelloFullName("Maria", "Garcia");PHP matches arguments to parameters by position: the first value you pass ("Maria") fills the first parameter ($firstName), and the second value ("Garcia") fills the second parameter ($lastName).
So far our functions have used echo to print text directly to the screen. But usually, you want a function to calculate something and hand the result back to you, so you can use it later — store it, combine it with other values, or display it differently. That is what return does.
<?php
function addNumbers($a, $b) {
$sum = $a + $b;
return $sum;
}
$result = addNumbers(4, 7);
echo "The total is: $result";Inside addNumbers, we calculate $a + $b and store it in $sum. The line return $sum; sends that value back out of the function to wherever it was called from. On the outside, $result = addNumbers(4, 7); grabs that returned value and stores it in a new variable called $result, which we then print. A key rule: as soon as PHP runs a return statement, the function stops immediately — any code written after it inside that function will never run.
Sometimes you want a parameter to have a sensible value already, so callers can skip it if they don't need to change it. You do this by writing an = sign and a value right in the function definition.
<?php
function greetUser($name, $greeting = "Hello") {
echo "$greeting, $name!";
}
greetUser("Maria");
greetUser("Ahmed", "Good morning");$greeting = "Hello" means: if nobody supplies a second argument, use "Hello" automatically. In the first call, greetUser("Maria"), only $name is given, so PHP falls back to the default and prints "Hello, Maria!". In the second call we override the default by passing "Good morning" explicitly, so it prints "Good morning, Ahmed!". Parameters with default values must be listed after parameters without defaults.
Scope means "which parts of your code can see a variable." Variables created inside a function are local — they only exist while that function is running, and code outside the function cannot see them.
<?php
function calculateSquare($number) {
$squared = $number * $number;
return $squared;
}
echo calculateSquare(5);
echo $squared;The first echo works fine and prints 25, because calculateSquare(5) returns the value directly. The second line, echo $squared;, causes a warning and prints nothing useful, because $squared was created inside the function and no longer exists once the function has finished running. This is a very common beginner mistake — remember that a function's internal variables stay private to that function unless you return them.
| Term | What it means | Example |
|---|---|---|
| Parameter | A placeholder variable named in the function definition | function add($a, $b) |
| Argument | The actual value you pass in when calling the function | add(4, 7) — here 4 and 7 are arguments |
| Return value | The result sent back out of the function with return | return $a + $b; |
PHP already comes with thousands of ready-made functions, called built-in functions, that you can call without defining them yourself. You have likely already used one: echo is a language construct, but strlen(), count(), and array_sum() are real built-in functions.
<?php
$fruits = ["apple", "banana", "mango"];
echo count($fruits);
echo strtoupper($fruits[0]);count($fruits) is a built-in function that returns how many items are in the array — 3 in this case. strtoupper($fruits[0]) is another built-in function that converts a string to uppercase letters, turning "apple" into "APPLE". You will use built-in functions constantly, and the functions you write yourself, like sayHello() earlier, work exactly the same way when you call them — PHP does not treat them any differently.
Functions become genuinely useful once you combine them with data, such as an array of prices. Here is a function that calculates the total of a shopping cart.
<?php
function calculateCartTotal($prices) {
$total = 0;
foreach ($prices as $price) {
$total += $price;
}
return $total;
}
$cart = [12.50, 8.00, 3.25];
echo "Cart total: $" . calculateCartTotal($cart);calculateCartTotal accepts one parameter, $prices, which we expect to be an array. Inside, $total starts at 0, and the foreach loop walks through every item in the array, adding each $price onto $total. Once the loop finishes, return $total; sends the final number back out. Outside the function, we call calculateCartTotal($cart) and join it to a string with the . operator to print a friendly message. If you have not worked with PHP arrays before, our PHP arrays guide below covers exactly how arrays like $prices and $cart work.
Not sure how arrays like $prices and $cart work yet? Start with our beginner-friendly guide to PHP arrays before diving deeper into functions.
Read: PHP Arrays for BeginnersA PHP function is a named, reusable block of code that performs a specific task. You define it once using the function keyword, then call it by name whenever you need that task done, instead of rewriting the same code repeatedly.
Use the return keyword followed by the value or variable you want to send back, such as return $total;. The function stops running immediately after the return statement, and you can store the result by assigning the function call to a variable, like $result = myFunction();.
A parameter is the placeholder variable named inside the parentheses when you define a function, such as $name in function greet($name). An argument is the actual value you supply when you call the function, such as "Maria" in greet("Maria").
Yes. Write an equals sign and a value after the parameter name in the function definition, like function greet($name, $greeting = "Hello"). If the caller does not supply that argument, PHP automatically uses the default value instead.
This is called variable scope. Variables created inside a PHP function are local to that function and disappear once the function finishes running. To use a value outside the function, you must return it and store the returned value in a variable in the outer code.
Functions are one of the most important building blocks in PHP. Once you are comfortable defining them, passing parameters in, and returning values out, you are ready to organize much larger programs — including the kind that read form data and talk to a database, which is exactly what our PHP form handling and database guides cover next.
Building something real with PHP and need a hand? Our team can help you plan, build, or review your project.
Get in touchOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
PostgreSQL ILIKE explained for beginners: search text without worrying about case, learn % and _ wildcards, and copy simple examples you can run today.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.