Current Location: Home> Latest Articles> How to Pass Arrays as Parameters in PHP - Complete Guide

How to Pass Arrays as Parameters in PHP - Complete Guide

M66 2025-07-29

How to Pass Arrays as Parameters in PHP?

In PHP, we can pass arrays as parameters to functions by explicitly specifying the array type hint before the function parameter. This ensures that the function accepts only array-type parameters. This approach allows you to handle large amounts of data or create reusable code blocks flexibly.

PHP Syntax for Passing Arrays as Parameters

The syntax for passing arrays as parameters is straightforward:

function myFunction(array $array) {

In this example:

  • $array is the array passed as a parameter.
  • array type hint ensures that the function only accepts array-type parameters.

Practical Example: Calculating the Maximum Value in an Array

Consider the following function that calculates the maximum value in an array:

function getMax(array $array) {
    if (empty($array)) {
        return null;
    }
    $max = $array[0];
    foreach ($array as $value) {
        if ($value > $max) {
            $max = $value;
        }
    }
    return $max;
}

We can call this function like this:

$array = [1, 3, 5, 7, 9];
$max = getMax($array); // $max will be 9

Conclusion

By passing arrays as parameters to functions, we can create more flexible and reusable code. This is especially useful when working with large datasets or creating general-purpose functions.