All posts
PHPSeptember 16, 20267 min read

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.

F
Fepiq Team
Fepiq

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.

What is a function in PHP?

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().

Why use functions instead of just writing code directly?

  • Avoid repetition: write the logic once, reuse it anywhere in your script.
  • Easier to read: a well-named function like calculateTotalPrice() explains what the code does without you reading every line.
  • Easier to fix bugs: if something is wrong, you only need to fix it in one place, not everywhere you copied the code.
  • Easier to test: you can check a small function on its own instead of testing your whole program at once.

The basic syntax of a PHP function

Here is the smallest possible PHP function: one that prints a greeting message.

php
<?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.

Passing information in with parameters

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
<?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
<?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).

Getting information out with return values

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
<?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.

Default parameter values

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
<?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.

Variable scope: where a variable can be used

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
<?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.

Parameter vs argument vs return value

TermWhat it meansExample
ParameterA placeholder variable named in the function definitionfunction add($a, $b)
ArgumentThe actual value you pass in when calling the functionadd(4, 7) — here 4 and 7 are arguments
Return valueThe result sent back out of the function with returnreturn $a + $b;

Built-in functions vs. functions you write

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
<?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.

A practical example: combining functions with arrays

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
<?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 Beginners

Common mistakes beginners make with PHP functions

  1. Forgetting the parentheses when calling a function, e.g. writing sayHello; instead of sayHello();.
  2. Expecting a variable defined inside a function to still exist outside it, without using return.
  3. Mixing up parameter order — passing arguments in the wrong sequence for a function with multiple parameters.
  4. Using echo inside a function when you actually need return, which stops you from reusing the result elsewhere.
  5. Naming two functions the same thing, which causes a fatal "cannot redeclare function" error.

Frequently asked questions

What is a function in PHP?+

A 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.

How do I return a value from a PHP function?+

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();.

What is the difference between a parameter and an argument in PHP?+

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").

Can a PHP function have default parameter values?+

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.

Why can't I access a variable outside the function it was created in?+

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 touch

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.