Parameters & Return Values in PHP: A Complete Beginner’s Guide
php parameters with example
Functions become powerful when you can pass data into them and receive results back. In PHP, this is done using parameters and return values. Understanding these two concepts helps you build dynamic, reusable, and professional PHP applications.
This guide explains parameters, arguments, return values, default values, type declarations, and includes examples to make learning easier.
Parameters are variables defined in the function declaration. They allow you to send data into a function.
Example:
function greet($name) {
echo "Hello, $name";
}
Here, $name is a parameter.
When calling:
greet("Shubham");
"Shubham" is an argument.
<?php
function displayAge($age) {
echo "Your age is $age";
}
displayAge(25);
?>
<?php
function add($a, $b) {
echo $a + $b;
}
add(5, 10); // Output: 15
?>
A default value is used when no argument is passed.
<?php
function greetUser($name = "Guest") {
echo "Welcome, $name!";
}
greetUser(); // Output: Welcome, Guest!
greetUser("Amit"); // Output: Welcome, Amit!
?>
PHP normally passes parameters by value, meaning the original variable is not changed.
<?php
function increment($num) {
$num++;
}
$value = 10;
increment($value);
echo $value; // Output: 10 (unchanged)
?>
Use & to modify the original value.
<?php
function incrementRef(&$num) {
$num++;
}
$value = 10;
incrementRef($value);
echo $value; // Output: 11
?>
PHP allows unlimited arguments using ... (variadic functions).
<?php
function sumAll(...$numbers) {
return array_sum($numbers);
}
echo sumAll(1, 2, 3, 4); // Output: 10
?>
A return value is the data that a function sends back to the calling code.
Syntax:
return value;
<?php
function multiply($x, $y) {
return $x * $y;
}
$result = multiply(5, 4);
echo $result; // Output: 20
?>
<?php
function test() {
echo "Step 1";
return;
echo "Step 2"; // This will NOT run
}
test();
?>
PHP allows you to specify what type of value a function should return.
<?php
function divide(int $a, int $b): float {
return $a / $b;
}
echo divide(10, 3);
?>
<?php
function getDiscount($price, $percent) {
return $price - ($price * $percent / 100);
}
echo getDiscount(1000, 20); // Output: 800
?>
<?php
function fullName($first, $last) {
return $first . " " . $last;
}
echo fullName("Shubham", "Mishra");
?>
These concepts help you:
Reuse code efficiently
Break logic into smaller functions
Reduce duplication
Improve readability
Build flexible, powerful PHP applications
Understanding parameters and return values is essential for writing clean, modular, and professional PHP functions. Master these basics, and you’ll be ready to handle more advanced concepts like recursion, OOP methods, and closures.