Menu
Coddy logo textTech

Return Type Declarations

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

Just as you can declare types for parameters, you can also specify what type a function should return. Return type declarations tell PHP exactly what kind of value your function will send back, helping catch errors when a function accidentally returns the wrong type.

To add a return type, place a colon followed by the type after the closing parenthesis of the parameter list:

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

echo add(5, 3);
?>

This outputs 8. The : int after the parentheses declares that this function must return an integer. If you tried to return a string instead, PHP would produce an error.

You can use the same types as parameter declarations: int, float, string, bool, and array. There's also a special type called void for functions that don't return anything:

<?php
function sayHello(string $name): void {
    echo "Hello, $name!\n";
}

sayHello("Alice");
?>

A void function cannot have a return statement with a value. Combining parameter types with return types makes your functions self-documenting—anyone reading the code immediately knows what goes in and what comes out.

challenge icon

Challenge

Easy

Read two lines of input:

  1. A price as a decimal number (e.g., 49.99)
  2. A discount percentage as a whole number (e.g., 20)

Create a function called calculateFinalPrice that accepts two parameters with type declarations:

  • $price as float
  • $discountPercent as int

The function must have a return type declaration of float and should return the final price after applying the discount.

Call the function with the input values and print the returned result.

Example 1:

If the inputs are 100.00 and 25, the output should be:

75

Example 2:

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

44.991

Example 3:

If the inputs are 200.50 and 50, the output should be:

100.25

Try it yourself

<?php
// Read input
$price = floatval(fgets(STDIN));
$discountPercent = intval(fgets(STDIN));

// TODO: Create a function called calculateFinalPrice with:
// - Parameter $price with float type declaration
// - Parameter $discountPercent with int type declaration
// - Return type declaration of float
// The function should return the final price after applying the discount


// Call the function and print the result
echo calculateFinalPrice($price, $discountPercent);
?>
quiz iconTest yourself

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

All lessons in Fundamentals