PHPLesson 9 of 13

Functions

A function is a named block of code you can call whenever you need it. Instead of copying the same lines into ten places, you write them once inside a function and call it by name. When the logic changes, you fix it in one spot.

A function is a named block of code you can call whenever you need it. Instead of copying the same lines into ten places, you write them once inside a function and call it by name. When the logic changes, you fix it in one spot.

You define a function with the function keyword, a name, and parentheses. Parameters go inside the parentheses and act like local variables that receive the values you pass in. The function runs its body and, at the end, returns a value with the return statement.

Calling a function looks like calling a built-in one: doubleIt(5) runs the body with 5 as the parameter. The return value lands where you called it, so you can echo it, store it in a variable, or pass it into another function.

Function names are case-insensitive in PHP, and a function must be defined before you call it. Parameters can have default values, so callers can skip them. As of PHP 8, parameters can also be typed, like int $price or string $name, and PHP enforces them.

Default values

A parameter with a default is optional at the call site. If the caller does not pass a value, PHP uses the default. Defaults must come after all required parameters in the list.

PHP
function greet($name, $greeting = "Hello") {
  return "$greeting, $name!";
}
echo greet("Aya");          // Hello, Aya!
echo greet("Aya", "Hi");    // Hi, Aya!

Typed parameters and returns

PHP 7 and 8 allow type declarations. The colon after the parentheses declares the return type. PHP checks both directions: wrong input or wrong return throws a TypeError instead of failing silently.

PHP
function doubleIt(int $number): int {
  return $number * 2;
}
echo doubleIt(21); // 42
echo doubleIt("x"); // TypeError

Syntax

PHP
<?php
function add($a, $b) {
  return $a + $b;
}

echo add(3, 4); // 7
?>

Missing return Gives null

Function without return gives null — like JS, forgetting return is #1 bug.

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

Good to know

  • function defines a reusable block; return sends a value back.
  • Parameters receive the values passed at the call site.
  • Defaults make parameters optional for callers.
  • Typed parameters and return types enforce correctness in PHP 7+.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground