Back to course

Function Parameters and Return Values

PHP: The Complete 0 to Hero Bootcamp

18. Function Parameters and Return Values

Functions are most useful when they can accept input and provide output.

Function Parameters (Input)

Parameters are variables listed inside the function definition parentheses. They act as placeholders for values passed when the function is called (arguments).

php

<?php function greetUser($name) { // $name is the parameter echo "Welcome, $name!"; } greetUser("Sam"); // 'Sam' is the argument echo "<br>"; greetUser("Maria"); ?>

Default Parameter Values

You can set a default value for a parameter. If the caller omits the argument, the default value is used.

php

<?php function calculateTax($price, $tax_rate = 0.10) { $total = $price * (1 + $tax_rate); echo "Total price: " . $total . "<br>"; } calculateTax(100); // Uses default rate (0.10) -> 110 calculateTax(100, 0.05); // Uses specified rate (0.05) -> 105 ?>

Function Return Values (Output)

The return statement immediately stops function execution and sends a value back to the caller. Unlike echo, return doesn't output to the browser; it provides data for processing.

php

<?php function addNumbers($a, $b) { $sum = $a + $b; return $sum; // Return the result } $result = addNumbers(5, 7); // $result now holds 12 echo "The result is: " . $result; ?>