Skip to content

PHP Tutorial Functions

Creating and Calling Functions

Lesson 102 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

A function is a named block of code that you can run whenever you want. You write it once and call it as many times as you need.

Think of a function as a recipe. You write the recipe once. Every time you want the dish, you follow the recipe instead of writing the steps again.

index.php
PHP
<?php
function sayHello(): void
{
    echo "Hello, welcome to PHP!\n";
}

sayHello();
sayHello();
Output
OUTPUT
Hello, welcome to PHP!
Hello, welcome to PHP!

The parts of a function

Text
PLAIN
function name(): returnType
{
    // the code
}
  • function is the keyword that starts it.
  • sayHello is the name. Follow the same rules as variable names, without the $.
  • () holds the parameters (empty here).
  • : void says the function returns nothing. Return types come soon.
  • { ... } holds the code.

Writing the function does not run it. It runs only when you call it by name followed by brackets.

Why use functions

  1. No repetition. Write the code once, use it everywhere.
  2. One place to fix. If the logic changes, you change it in one spot.
  3. Readable code. calculateTax() says more than ten lines of maths.
  4. Easy testing. A small function is easy to check on its own.

A function can call another function

index.php
PHP
<?php
function printLine(): void
{
    echo str_repeat("-", 20) . "\n";
}

function printHeader(): void
{
    printLine();
    echo "MY SHOP\n";
    printLine();
}

printHeader();
Output
OUTPUT
--------------------
MY SHOP
--------------------

Where to define functions

In PHP you can call a function before the line where it is defined, as long as it is defined at the top level of the file (not inside an if).

index.php
PHP
<?php
echo greet();   // works, even though greet() is defined below

function greet(): string
{
    return "Hi!";
}
Output
OUTPUT
Hi!

Naming

Name functions with a verb: getUser(), calculateTotal(), isValidEmail(). Use camelCase. A good name tells you what the function does without reading it.

info
Built-in functions
PHP has thousands of ready-made functions such as strlen() and count(). You have been calling them all along. Your own functions work the same way.

Write a function printFooter() that prints Copyright 2026. Call it twice.

Show a possible solution
index.php
PHP
<?php
function printFooter(): void
{
    echo "Copyright 2026\n";
}

printFooter();
printFooter();
Output
OUTPUT
Copyright 2026
Copyright 2026