Menu
Coddy logo textTech

Recap - Creating Reusable Code

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

challenge icon

Challenge

Easy

Read three lines of input:

  1. An item name (e.g., Coffee)
  2. A base price as a decimal number (e.g., 4.50)
  3. A quantity as a whole number (e.g., 3)

Create a function called calculateTotal that combines everything you've learned about functions:

  • Parameters: $item (string), $price (float), $quantity (int with default value of 1)
  • Return type: string

Inside the function:

  • Create a local variable $subtotal to store the result of $price * $quantity
  • Return a string in the format: [quantity]x [item] = $[subtotal]

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

Example 1:

If the inputs are Coffee, 4.50, and 3, the output should be:

3x Coffee = $13.5

Example 2:

If the inputs are Sandwich, 8.99, and 2, the output should be:

2x Sandwich = $17.98

Example 3:

If the inputs are Muffin, 3.25, and 5, the output should be:

5x Muffin = $16.25

Try it yourself

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

// TODO: Create the calculateTotal function below
// - Parameters: $item (string), $price (float), $quantity (int with default value of 1)
// - Return type: string
// - Inside: create $subtotal variable and return formatted string



// Call the function and print the result

?>

All lessons in Fundamentals