PHP Functions

A function is a named block of reusable code that performs a specific task. Instead of writing the same code in multiple places throughout a script, a function encapsulates that logic once and makes it callable from anywhere. Functions improve code organization, reduce repetition, and make programs easier to maintain and debug.

Defining and Calling a Function

A function is created using the function keyword, followed by the function name, parentheses, and a code block enclosed in curly braces.

<?php
  function greet() {
    echo "Hello! Welcome to our website.";
  }

  greet();   // Outputs: Hello! Welcome to our website.
  greet();   // Call it again - outputs the same message
?>

The function is defined once but can be called any number of times.

Function Naming Rules

  • Names begin with a letter or underscore — never a number.
  • Names can contain letters, numbers, and underscores.
  • Function names are case-insensitive in PHP, but the convention is to use lowercase with underscores or camelCase.
  • Avoid using names that conflict with PHP's built-in functions.

Functions with Parameters

Parameters allow a function to receive input values that affect its behavior. They are listed inside the parentheses in the function definition.

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

  greetUser("Alice");   // Outputs: Hello, Alice!
  greetUser("Bob");     // Outputs: Hello, Bob!
?>

When the function is called, the value passed in (the argument) is assigned to the parameter variable inside the function.

Multiple Parameters

<?php
  function calculateArea($length, $width) {
    $area = $length * $width;
    echo "Area: " . $area . " square meters.";
  }

  calculateArea(10, 5);    // Outputs: Area: 50 square meters.
  calculateArea(8, 3);     // Outputs: Area: 24 square meters.
?>

Default Parameter Values

A parameter can be given a default value. If no argument is passed for that parameter when the function is called, the default is used automatically.

<?php
  function createGreeting($name, $timeOfDay = "morning") {
    echo "Good " . $timeOfDay . ", " . $name . "!";
  }

  createGreeting("Sarah");              // Outputs: Good morning, Sarah!
  createGreeting("Tom", "evening");     // Outputs: Good evening, Tom!
?>

Parameters with default values must come after parameters without defaults.

Returning Values

A function can send a result back to the caller using the return statement. The returned value can be stored in a variable or used directly in an expression.

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

  $result = addNumbers(15, 27);
  echo $result;   // Outputs: 42

  echo addNumbers(100, 200);   // Outputs: 300 - used directly
?>

The return statement also immediately exits the function — any code after it is not executed.

Returning Multiple Values via Array

<?php
  function getMinMax($numbers) {
    return [
      "min" => min($numbers),
      "max" => max($numbers)
    ];
  }

  $scores = [88, 42, 95, 67, 100];
  $result = getMinMax($scores);

  echo "Min: " . $result['min'];   // Outputs: Min: 42
  echo "Max: " . $result['max'];   // Outputs: Max: 100
?>

Type Declarations

PHP 7+ supports type declarations for parameters and return values. This enforces that the correct data type is used.

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

  echo multiply(4, 5);   // Outputs: 20
  // multiply("4", 5)    // PHP will coerce "4" to 4, or throw an error in strict mode
?>

Passing Arguments by Reference

By default, PHP passes arguments by value — the function receives a copy of the variable and the original is unchanged. Using & passes the argument by reference, allowing the function to modify the original variable.

<?php
  function addTen(&$value) {
    $value += 10;
  }

  $score = 50;
  addTen($score);
  echo $score;   // Outputs: 60 - original variable was modified
?>

Variable Number of Arguments

The ...$args syntax (spread operator) allows a function to accept any number of arguments.

<?php
  function sumAll(...$numbers) {
    return array_sum($numbers);
  }

  echo sumAll(1, 2, 3);           // Outputs: 6
  echo sumAll(10, 20, 30, 40);    // Outputs: 100
  echo sumAll(5);                 // Outputs: 5
?>

Anonymous Functions (Closures)

An anonymous function has no name. It is assigned to a variable or passed as an argument to another function.

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

  $greet("Emma");   // Outputs: Hi, Emma!
?>

Anonymous functions are commonly used as callbacks in functions like array_map() and usort().

Arrow Functions (PHP 7.4+)

Arrow functions are a shorter syntax for simple anonymous functions. They automatically capture variables from the surrounding scope.

<?php
  $multiplier = 3;
  $triple = fn($n) => $n * $multiplier;

  echo $triple(7);    // Outputs: 21
  echo $triple(10);   // Outputs: 30
?>

Key Points

  • Functions are defined with the function keyword and called by their name followed by parentheses.
  • Parameters allow functions to receive input; multiple parameters are separated by commas.
  • Default parameter values are used when no argument is provided for that parameter.
  • The return statement sends a value back to the caller and exits the function.
  • Passing by reference (&) allows a function to modify the original variable.
  • The spread operator (...$args) accepts a variable number of arguments.
  • Anonymous functions and arrow functions provide compact, inline alternatives to named functions.

Leave a Comment

Your email address will not be published. Required fields are marked *