HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Return Values

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.


1. The return Statement

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
?>

2. Capturing a Return Value

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";
?>

3. Return Type Declarations (PHP 7+)

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);
?>
Immediate Exit: Any code placed after a return statement inside a function will never be executed.
Pro Tip: Use functions with return values to keep your logic separate from your display code. Calculate the data in a function, return it, and echo it only when needed.

Key Points to Remember

  • The return keyword sends a value back to the caller.
  • A function stops immediately once a return is executed.
  • You can store return values in variables for later use.
  • Type hinting (e.g., : int) ensures your function returns the correct data format.
  • Functions should generally **calculate and return**, not just echo, to stay reusable.