Menu
Coddy logo textTech

Returning Values

Part of the Fundamentals section of Coddy's PHP journey — lesson 63 of 71.

The functions we've created so far use echo to display output directly. But often, you want a function to calculate something and give the result back to you, so you can use it elsewhere in your code. This is where the return statement comes in.

The return statement sends a value back to wherever the function was called:

<?php
function add($a, $b) {
    return $a + $b;
}

$result = add(5, 3);
echo $result;
?>

This outputs 8. Instead of printing the sum inside the function, we return it. The calling code receives that value and stores it in $result.

Returning values makes functions much more versatile. You can use the returned value in calculations, pass it to other functions, or store it for later:

<?php
function double($num) {
    return $num * 2;
}

echo double(5) + double(3);
?>

This outputs 16 (10 + 6). Each call to double() returns a value that gets used in the addition.

One important thing to know: when PHP hits a return statement, the function stops immediately. Any code after return won't execute.

challenge icon

Challenge

Easy

Read two lines of input:

  1. A number representing the base of a rectangle (e.g., 5)
  2. A number representing the height of a rectangle (e.g., 3)

Create a function called calculateArea that accepts two parameters: $base and $height. The function should return the area of the rectangle (base × height).

Call the function with the input values, store the returned value in a variable, and print the result.

Example 1:

If the inputs are 5 and 3, the output should be:

15

Example 2:

If the inputs are 10 and 7, the output should be:

70

Example 3:

If the inputs are 12 and 4, the output should be:

48

Cheat sheet

The return statement sends a value back to wherever the function was called, allowing you to use the result elsewhere in your code:

<?php
function add($a, $b) {
    return $a + $b;
}

$result = add(5, 3);
echo $result; // Outputs: 8
?>

Returned values can be used in calculations or passed to other functions:

<?php
function double($num) {
    return $num * 2;
}

echo double(5) + double(3); // Outputs: 16
?>

When PHP hits a return statement, the function stops immediately. Any code after return won't execute.

Try it yourself

<?php
// Read input
$base = intval(fgets(STDIN));
$height = intval(fgets(STDIN));

// TODO: Create a function called calculateArea that accepts $base and $height parameters
// The function should return the area (base × height)


// TODO: Call the function with the input values and store the result in a variable


// Output the result
echo $result;
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals