Arithmetic Operators
Part of the Fundamentals section of Coddy's PHP journey — lesson 15 of 71.
Now that you know how to work with variables and data types, let's perform calculations with them. PHP provides four basic arithmetic operators that work just like in math:
| Operator | Operation | Example |
+ | Addition | 5 + 3 → 8 |
- | Subtraction | 10 - 4 → 6 |
* | Multiplication | 6 * 7 → 42 |
/ | Division | 20 / 4 → 5 |
You can use these operators with numbers directly or with variables:
<?php
$price = 25;
$quantity = 4;
$total = $price * $quantity;
echo $total; // Outputs: 100
?>You can also combine multiple operations in a single expression:
<?php
$result = 10 + 5 - 3;
echo $result; // Outputs: 12
?>Challenge
EasyRead three numbers from input: a price, a quantity, and a discount amount.
Calculate the total cost by multiplying the price by the quantity, then subtract the discount from that result.
Print the final total.
Example:
If the inputs are 50, 3, and 25, the output should be 125 (because 50 × 3 - 25 = 125).
Cheat sheet
PHP provides four basic arithmetic operators:
| Operator | Operation | Example |
+ | Addition | 5 + 3 → 8 |
- | Subtraction | 10 - 4 → 6 |
* | Multiplication | 6 * 7 → 42 |
/ | Division | 20 / 4 → 5 |
Use operators with variables:
<?php
$price = 25;
$quantity = 4;
$total = $price * $quantity;
echo $total; // Outputs: 100
?>Combine multiple operations:
<?php
$result = 10 + 5 - 3;
echo $result; // Outputs: 12
?>Try it yourself
<?php
// Read input
$price = intval(fgets(STDIN));
$quantity = intval(fgets(STDIN));
$discount = intval(fgets(STDIN));
// TODO: Write your code below to calculate the total cost
// Output the result
echo $total;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables 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