Recap - Creating Reusable Code
Part of the Fundamentals section of Coddy's PHP journey — lesson 68 of 71.
Challenge
EasyRead three lines of input:
- An item name (e.g.,
Coffee) - A base price as a decimal number (e.g.,
4.50) - 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 of1) - Return type:
string
Inside the function:
- Create a local variable
$subtotalto 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.5Example 2:
If the inputs are Sandwich, 8.99, and 2, the output should be:
2x Sandwich = $17.98Example 3:
If the inputs are Muffin, 3.25, and 5, the output should be:
5x Muffin = $16.25Try 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
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic7Arrays Part 2 - Associative
Intro to Associative ArraysAccessing Values by KeyModifying Values by KeyAdding New Key-Value PairsCheck if Key ExistsRecap - Key-Value Data Store10Functions
Declaring & Calling FunctionsFunction ParametersReturning ValuesDefault Parameter ValuesType Declarations for ParamsReturn Type DeclarationsVariable ScopeRecap - Creating Reusable Code2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators