πŸ“ Web Development

PHP Functions: Parameters, Return Values and Scope

Aug 17, 20265 min read6 viewsBy Flow

PHP functions let you name a block of code and run it whenever you want β€” as many times as you want β€” without writing it out again.

You have been using them already. count(), implode() and sort() are all functions, and the brackets are the giveaway: you call a function by writing its name followed by ().

Be careful with that rule though. if (), while () and foreach () have brackets too, and they are not functions β€” they are language constructs built into PHP. Brackets alone do not make something a function. Being a named block you can call does.

PHP gives you two kinds:

  • Built-in functions β€” the ones that ship with PHP, like the count(), implode() and sort() you met in PHP arrays.
  • User-defined functions β€” the ones you write yourself, with your own name and your own rules.

This lesson is about the second kind.

Writing your first function

A function has two halves. You define it once, then call it as many times as you like.

<?php
function sayHello() {
    echo "Hello from a function!<br>";
}

sayHello();
sayHello();
?>

Output:

PHP functions output: calling sayHello twice prints Hello from a function on two lines

Read it in order. The function keyword names the block. Nothing inside runs at that moment. It only runs when you write sayHello(); β€” and here that happens twice, so the line prints twice.

That is the whole idea. Write it once, run it as often as you need.

Passing data in with parameters

A function that always does exactly the same thing is not much use. Parameters let you hand it something to work with.

<?php
function greet($name) {
    echo "Hello, " . $name . "!<br>";
}

greet("Ayesha");
greet("Bilal");
?>

Output:

PHP functions with a parameter printing Hello, Ayesha and Hello, Bilal

$name is a parameter β€” a placeholder that only exists inside the function. "Ayesha" is an argument β€” the actual value you pass in.

People use the two words interchangeably and nothing breaks. But knowing the difference makes error messages readable, and PHP talks about arguments constantly.

You can take more than one.

<?php
function orderTotal($price, $quantity) {
    echo "Total: " . ($price * $quantity) . "<br>";
}

orderTotal(250, 3);
orderTotal(99, 10);
?>

Output:

PHP functions with two parameters printing Total: 750 and Total: 990

Order matters. The first argument lands in the first parameter, the second in the second. Swap them by accident and PHP will not warn you β€” it will multiply the wrong way round and hand you a number that looks fine.

return: the part that trips everyone up

So far these functions echo straight to the page. That is fine for learning, and wrong for almost everything else.

return hands the answer back to whoever called the function, instead of printing it.

<?php
function addTax($amount) {
    return $amount * 1.17;
}

$total = addTax(1000);

echo $total . "<br>";
echo addTax(500);
?>

Output:

PHP functions return value output showing 1170 and 585 after adding tax

Look at what that buys you. The result went into $total, so you can store it, compare it, or feed it into another function. An echo inside the function would have printed it and thrown it away.

The rule is short: a function should calculate and return. Printing is the caller’s job.

One more thing about return β€” it stops the function immediately. Any lines after it never run.

<?php
function checkAge($age) {
    if ($age < 18) {
        return "Too young";
    }

    return "Allowed";
}

echo checkAge(15) . "<br>";
echo checkAge(22);
?>

Output:

PHP functions early return output printing Too young for 15 and Allowed for 22

When the age is 15 the first return fires and the function is done β€” the second one is never reached. Checking the failing case first and returning early keeps functions flat and easy to read.

Default values

Give a parameter a default and the argument becomes optional.

<?php
function greetUser($name, $greeting = "Hello") {
    echo $greeting . ", " . $name . "!<br>";
}

greetUser("Sara");
greetUser("Sara", "Good morning");
?>

Output:

PHP functions default parameter output: Hello, Sara! then Good morning, Sara!

Parameters with defaults must come last. PHP fills them left to right, so an optional one sitting before a required one leaves it no way to know what you meant.

Scope: variables live inside

This is where beginners lose an afternoon. A variable made inside a function does not exist outside it. And a variable outside is invisible inside.

<?php
$message = "I am outside";

function showMessage() {
    echo isset($message) ? $message : "Nothing here";
}

showMessage();
?>

Output:

PHP functions variable scope output printing Nothing here because the outside variable is invisible

$message exists, and the function still cannot see it. That is not a bug β€” it is the point. Functions are sealed boxes, which is exactly why you can drop one into another project without it quietly breaking something.

Need a value inside? Pass it in as a parameter. Need one out? return it. Those two doors are enough for almost everything you will write.

Three mistakes with PHP functions

Echoing when you meant to return. If you cannot store the result in a variable, the function printed instead of returning. This is the most common one by far.

Forgetting the parentheses. sayHello; does nothing useful. sayHello(); calls it. The brackets are what run the code.

Expecting outside variables to be visible. They are not. Pass what you need as a parameter β€” reaching for global is almost always the wrong fix, and it makes the function depend on the rest of your file.

Common questions about PHP functions

The questions that follow almost everyone’s first few functions.

What is the difference between echo and return in a PHP function?

echo prints straight to the page and throws the value away. return hands the value back to whoever called the function, so you can store it in a variable or pass it on. If you cannot store the result, the function echoed instead of returning.

Why can my function not see a variable declared outside it?

That is variable scope, and it is deliberate. A function is a sealed box: it cannot see outside variables, and its own variables do not leak out. Pass what you need in as a parameter and return what you need back.

What is the difference between a parameter and an argument?

The parameter is the placeholder in the function definition, like $name. The argument is the actual value you pass when calling it, like "Ayesha". People use the words interchangeably, but PHP error messages talk about arguments.

Can a PHP function return more than one value?

Not directly β€” but you can return an array containing several values, and unpack it with [$a, $b] = myFunction();. That is the normal way to hand back more than one result.

What is next

PHP functions are how code stops being a long script and starts being something you can reuse and trust. Everything from here β€” forms, database queries, whole frameworks β€” is built from them.

If loops or arrays still feel shaky, go back through PHP loops and PHP arrays. Both come up constantly once you start writing functions of your own.

Comments

Loading comments...

Link copied to clipboard