PHP Function Parameters (Step-by-Step Guide with Examples)
In PHP, function parameters allow you to pass values to functions and control their behavior. Parameters make functions more dynamic and reusable by modifying their output based on input values.
What Are Function Parameters in PHP?
Parameters are variables listed inside the function parentheses ()`. When calling the function, you provide arguments (actual values) that are assigned to these parameters.
Syntax of a Function with Parameters
function functionName($param1, $param2) {
// Function code
}
Passing Parameters to PHP Functions
Example: Function with One Parameter
<?php
function greetUser($name) {
echo "Hello, $name!";
}
greetUser("John"); // Calling function with argument
?>
➡ The $number remains unchanged outside the function.
Passing Arguments by Reference (Using &)
To modify the original variable inside a function, use & (pass by reference).
Example: Pass by Reference
<?php
function increment(&$num) {
$num++;
}
$number = 10;
increment($number);
echo "New Value: $number"; // The original variable is modified
?>
Output:
NewValue: 11
➡ The $numberchanges globally because we passed it by reference.
Using func_get_args() to Accept Unlimited Arguments
PHP allows functions to accept an unlimited number of arguments using func_get_args().
Example: Function with Dynamic Parameters
<?php
function sumAll() {
$args = func_get_args(); // Get all arguments as an array
$sum = array_sum($args); // Calculate sum
echo "Total Sum: $sum";
}
sumAll(5, 10, 15, 20);
?>
Output:
TotalSum:50
Using ... (Variadic Functions) for Multiple Arguments
PHP 5.6+ supports variadic functions using ... (spread operator) to accept any number of arguments.
Use meaningful parameter names Set default values where possible Use type hints (e.g., int, string, array) for better validation Use pass-by-reference (&) when modifying values inside the function Keep functions short and focused