While some functions perform actions (like echoing text), others calculate a result and "give it back" to the script. This is done using the return statement. Once a return is executed, the function stops immediately.
Think of the return statement as the "answer" to the function's question. The value is sent back to where the function was called.
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10); // Outputs: 5 + 10 = 15
?>
Usually, you want to store the result of a function in a variable so you can use it later in your script.
<?php
function calculateTax($price) {
return $price * 0.15;
}
$itemPrice = 100;
$taxAmount = calculateTax($itemPrice);
echo "Item price: $itemPrice, Tax: $taxAmount";
?>
In modern PHP, you can explicitly state what type of data your function must return by adding a colon and the type after the parentheses.
<?php
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
return statement inside a function will never be executed.
: int) ensures your function returns the correct data format.