Beginner Fundamentals

PHP Functions

A function is a reusable block of code that performs a task. You write it once and call it whenever you need it.

Defining a function

Use the function keyword followed by a name and parentheses.

<?php
function sayHello() {
    echo "Hello!";
}

sayHello(); // Hello!

Parameters

Pass values into a function through parameters.

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

greet("Lucas"); // Hello, Lucas!

Return values

Use return to send a result back to the caller.

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

$sum = add(3, 4);
echo $sum; // 7

Default values

A parameter can have a default used when no argument is given.

<?php
function greet($name = "Guest") {
    echo "Hello, $name!";
}

greet();        // Hello, Guest!
greet("Ana");   // Hello, Ana!

Type hints

You can declare the expected types for parameters and the return value.

<?php
function multiply(int $a, int $b): int {
    return $a * $b;
}

echo multiply(2, 5); // 10