Tsallaka zuwa abun ciki
Justice Tech School

Functions

Define a function with function. Parameters can have default values and type declarations, and a return type can follow a colon. Arguments can be passed by name (named arguments). Variadic functions collect extra values with ...$args.

Example
function greet(string $name = "friend"): string {
  return "Hello, $name";
}
function sum(int ...$nums): int {
  return array_sum($nums);
}
function area(int $w, int $h): int {
  return $w * $h;
}
echo greet(), "\n";
echo greet("Ada"), "\n";
echo sum(1, 2, 3, 4), "\n";
echo area(h: 5, w: 4), "\n";

Result

Hello, friend
Hello, Ada
10
20

Exercise

Send a value back.

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

Quiz Test

What does ...$nums collect?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.