PHP Function Parameters : A Tutorial with Examples

PHP functions can accept parameters (also called arguments) to make them more dynamic and reusable. Function parameters allow you to pass data into a function for processing.

PHP offers different ways to define and work with function parameters, including optional parameters, default values, passing by reference, and variable-length parameter lists.

In this tutorial, we will cover:

Let’s explore each concept with examples and explanations.

1. Basic Function Parameters

In PHP, you can define functions with parameters that allow you to pass values into the function. When calling the function, you provide arguments that correspond to these parameters.

Syntax:

function functionName($param1, $param2) {
    // Function body
}

Example (Function with Parameters):

<?php
// Function to greet a user
function greet($name, $greeting) {
    echo "$greeting, $name!\n";
}

// Call the function with arguments
greet("Alice", "Hello");  // Outputs: Hello, Alice!
greet("Bob", "Good morning");  // Outputs: Good morning, Bob!
?>
  • In this example, the function greet() accepts two parameters: $name and $greeting. The values passed as arguments when calling the function are used to form the greeting message.

2. Default Parameter Values

PHP allows you to define default values for function parameters. If the function is called without providing an argument for a parameter with a default value, PHP will use the default value.

Example (Default Parameter Values):

<?php
// Function to greet a user with a default greeting
function greet($name, $greeting = "Hello") {
    echo "$greeting, $name!\n";
}

// Call the function with and without the second argument
greet("Alice");  // Outputs: Hello, Alice!
greet("Bob", "Good evening");  // Outputs: Good evening, Bob!
?>
  • In this example, the parameter $greeting has a default value of “Hello”. When the function is called without providing a value for $greeting, the default value is used.

3. Passing Arguments by Reference

By default, function parameters in PHP are passed by value, meaning that the function gets a copy of the argument, and changes to the parameter do not affect the original variable. However, you can pass parameters by reference using the & symbol, allowing the function to modify the original variable.

Example (Passing Arguments by Reference):

<?php
// Function to add 10 to a number by reference
function addTen(&$number) {
    $number += 10;
}

// Original variable
$value = 20;

// Call the function, passing the variable by reference
addTen($value);
echo "Updated value: $value\n";  // Outputs: Updated value: 30
?>
  • In this example, the function addTen() modifies the value of $number directly because the parameter is passed by reference using &. The original variable $value is updated after calling the function.

4. Type Hinting in Function Parameters

PHP allows you to enforce type hinting for function parameters. This ensures that the arguments passed to the function are of a specific data type, such as int, float, string, array, or custom object types. If the argument doesn’t match the expected type, PHP will throw a TypeError.

Example (Type Hinting with Scalar Types):

<?php
// Function with type-hinted parameters
function multiply(int $a, int $b): int {
    return $a * $b;
}

// Call the function with integers
echo multiply(3, 4);  // Outputs: 12

// Uncommenting the following line will cause a TypeError
// echo multiply(3.5, 4);
?>
  • In this example, the parameters $a and $b are expected to be of type int. If you try to pass a value of a different type (like a float or string), PHP will throw a TypeError.

Example (Type Hinting with Arrays):

<?php
// Function that expects an array as a parameter
function sumArray(array $numbers): int {
    return array_sum($numbers);
}

// Call the function with an array
echo sumArray([1, 2, 3, 4]);  // Outputs: 10
?>
  • In this example, the function sumArray() expects an array as its parameter. If a non-array value is passed, PHP will throw a TypeError.

5. Variable-Length Parameter Lists (… Operator)

PHP supports variable-length parameter lists, allowing you to pass an arbitrary number of arguments to a function. You can use the … operator (also known as the “splat operator”) to accept multiple arguments as an array.

Example (Variable-Length Parameter List):

<?php
// Function that accepts a variable number of arguments
function sum(...$numbers) {
    return array_sum($numbers);
}

// Call the function with different numbers of arguments
echo sum(1, 2, 3);  // Outputs: 6
echo sum(5, 10, 15, 20);  // Outputs: 50
?>
  • In this example, the sum() function accepts a variable number of arguments. All the arguments passed to the function are collected into the $numbers array, which is then summed using array_sum().

Example (Combining Fixed and Variable-Length Parameters):

You can combine regular parameters and variable-length parameters in the same function. The variable-length parameter should always be the last parameter.

<?php
// Function that accepts a fixed parameter and a variable-length parameter list
function multiply($factor, ...$numbers) {
    return array_map(fn($n) => $n * $factor, $numbers);
}

// Call the function
$result = multiply(2, 1, 2, 3);
print_r($result);  // Outputs: Array ( [0] => 2 [1] => 4 [2] => 6 )
?>
  • In this example, the multiply() function takes a fixed parameter $factor and a variable-length list of numbers. The function multiplies each number by the $factor.

6. Example Use Case: Function with Multiple Parameter Types

Let’s create a more practical function that accepts multiple types of parameters, including type hinting, optional parameters, and a variable-length parameter list.

Example (Advanced Function with Multiple Parameter Types):

<?php
// Function that accepts a product name, price, and an optional list of tags
function addProduct(string $name, float $price, ...$tags) {
    echo "Product: $name\n";
    echo "Price: $" . number_format($price, 2) . "\n";

    if (!empty($tags)) {
        echo "Tags: " . implode(", ", $tags) . "\n";
    } else {
        echo "No tags provided.\n";
    }
}

// Call the function with different sets of parameters
addProduct("Laptop", 999.99, "Electronics", "Portable", "Gadgets");
addProduct("Book", 19.95);  // No tags provided
?>

Output:

Product: Laptop
Price: $999.99
Tags: Electronics, Portable, Gadgets

Product: Book
Price: $19.95
No tags provided.
  • In this example, the addProduct() function accepts a string ($name), a float ($price), and an optional list of tags (variable-length parameter). It prints out the product details and handles the presence or absence of tags gracefully.

Summary of PHP Function Parameters:

Concept Description
Basic Parameters Define parameters that must be provided when calling the function.
Default Values Allow parameters to have default values if no argument is provided.
Passing by Reference Use & to modify the original variable passed to the function.
Type Hinting Enforce specific data types for parameters (e.g., int, string).
Variable-Length Parameters Use … to accept a variable number of arguments.

Conclusion

PHP provides powerful mechanisms for working with function parameters, including passing by reference, setting default values, enforcing type hints, and handling variable-length argument lists.

In this tutorial, we covered:

  • Basic function parameters for passing values to functions.
  • Default parameter values for making parameters optional.
  • Passing by reference to modify the original variables.
  • Type hinting to enforce specific data types.
  • Variable-length parameter lists for handling an arbitrary number of arguments.

Related posts

PHP Static Methods: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

PHP Copying Files: A Tutorial with Examples