PHP Functions

User-defined functions, types and arrow functions.

✍️ 2 exercises in this lesson

Define a function with function name($param) { ... }.

  • Default values: function greet($name = "Guest")
  • Type declarations: function add(int $a, int $b): int
  • Named arguments (PHP 8): greet(name: "Ali")
  • Pass by reference with &: function addOne(&$n)
  • Arrow functions: fn($x) => $x * 2

Add declare(strict_types=1); at the top of a file to make type checks strict.

Key Takeaways: PHP Functions

Mastering PHP Functions helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Functions Code Example

PHP
<?php
declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

function greet(string $name = "Guest", string $greeting = "Hello"): string {
    return "$greeting, $name!";
}

$double = fn($n) => $n * 2;

echo add(5, 7) . "<br>";
echo greet() . "<br>";
echo greet(greeting: "Assalam-o-Alaikum", name: "Usman") . "<br>";
echo $double(21);
Output
12
Hello, Guest!
Assalam-o-Alaikum, Usman!
42
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP Functions Practice Exercises

Check what you learned in “PHP Functions”.

/ 2 solved
Fill in the blank

Declare the return type of the function.

function add(int $a, int $b) { return $a + $b; }
✓ Correct! Not quite. Try again.
Multiple choice

Which is a PHP arrow function?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services