Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Functions

A function is a named piece of code that you can call many times. Functions remove repetition and give parts of a program meaningful names.

Declaring and calling

A function is declared with the function keyword. The name is followed by parentheses, and the code it runs goes in curly braces:

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

The declaration itself runs nothing — the code inside executes only when the function is called. You can call a function as many times as you like.

Parameters

Parameters go in the parentheses — they are the data the function receives when called:

<?php
 
function sayHello($name)
{
    echo "Hello, $name!";
}
 
sayHello('Anna'); // Hello, Anna!

Returning a value

The return statement hands the result back to the place where the function was called. You can store it, pass it on or use it in an expression:

<?php
 
function square($n)
{
    return $n * $n;
}
 
$total = square(3) + square(4);
 
echo $total; // 25

A function that returns is more flexible than one that echoes: it does not decide for you what to do with the result.

Default values

A parameter can have a default value — then you may leave it out when calling:

<?php
 
function power($base, $exponent = 2)
{
    return $base ** $exponent;
}
 
echo power(3); // 9

Parameters with defaults go at the end of the list.

Types

You can state a type before a parameter and, after the colon, the type of the result. PHP checks that suitable values are passed in and reports an error immediately rather than somewhere unexpected later:

<?php
 
function double(int $n): int
{
    return $n * 2;
}
 
echo double(5); // 10

Types are optional, but real projects declare them almost everywhere.

Scope

Variables created inside a function do not exist outside it. The reverse also holds: a function does not see outer variables — pass in whatever it needs through parameters.

<?php
 
function triple(int $n): int
{
    $result = $n * 3;
 
    return $result;
}
 
echo triple(5); // 15

After the call the $result variable is gone. That is why functions do not interfere with each other even when they use the same names.

Arrow functions

A short function can be written on one line and stored in a variable:

<?php
 
$square = fn ($n) => $n * $n;
 
echo $square(4); // 16

Such functions are convenient to pass to other functions. For example, array_map() applies a function to every element of an array:

<?php
 
$square = fn ($n) => $n * $n;
 
echo implode(', ', array_map($square, [1, 2, 3])); // 1, 4, 9

Thanks for reading!

Donate to the site — we work hard for you.