PHP Functions

I. Why should we use functions?

  • Organize our code
  • Avoid repetitive code
  • Break complex code into logical chunks

II. Define your own function

We can use the function keyword to define a function.

We name the function and take optional argument variables. The body of the function is in a block of code { }

function sumNum(int $x, int $y) {
    echo $x + $y;
echo sumNum(1,2); // 3

III. Function names

Below are some rules for function names.

  • Similar to variable names but do not start with a dollar sign
  • Start with a letter or underscore.
  • Consist of letters, numbers, and underscores.
  • When naming a function, we should avoid built-in function names.
  • It’s not case-sensitive.

IV. return keyword

Often a function will take its arguments, do something, and return a value.

The return keyword is used for this.

function greeting() {
    return "Hello";
echo greeting() . " Anna";
// Output: Hello Anna

V. Return type declaration

PHP automatically figures out a data type of the variable, depending on its value.

We can declare the type using a colon : and data type before the curly bracket.

function hi(): int {
    return 1;
var_dump(hi()); // int(1)

We can add the question mark ? before the data type to accept the type as null and data type.

function hi(): ?int {
    return null;
var_dump(hi()); // NULL

We can return different data types using | or multiple data types using the mixed keyword.

function hi(): int|float {
    return 2.2;
var_dump(hi()); // float(2.2)

function hello(): mixed {
    return "Hey";
var_dump(hello()); //  string(3) "Hey"

VI. Variadic functions

PHP variadic function accepts many arguments.

When we place the … operator before a parameter, the function will accept a variable number of arguments.

function sum(...$numbers) {
    $total = 0;
    foreach($numbers as $number) {
        $total += $number;
    return $total;
echo sum(10, 20, 30, 40, 50); // 150

VII. Check if a function exists

We use the function_exists() function to check whether or not a function exists.

if (function_exists("array_combine")){
    echo "Function exists";
} else {
    echo "Function does not exist";

VIII. Built-in PHP functions

PHP has several built-in functions to perform a specific task.

Here are some examples.

echo strrev(" .dlrow olleH") . "</br>";
echo str_repeat("Ha ", 2) . "</br>";
echo strtoupper("hooray!") . "</br>";
echo strlen("intro") . "</br>";

/* Output:
Hello world.
Ha Ha

IX.Arrow function

Arrow function is a cleaner syntax of an anonymous function. It is especially used in a call-back function.

Arrow function has a single expression. We can use the fn keyword to create arrow functions.


fn(arguments) => expression;


$array = [1,2,3];
$array2 = array_map(fn($num) => $num * $num, $array);

echo "<pre>";
echo "</pre>";
    [0] => 1
    [1] => 4
    [2] => 9