0
0
PhpHow-ToBeginner · 2 min read

PHP How to Convert Celsius to Fahrenheit with Example

To convert Celsius to Fahrenheit in PHP, use the formula F = (C * 9/5) + 32 where C is the Celsius value; for example, $fahrenheit = ($celsius * 9 / 5) + 32;.
📋

Examples

Input0
Output32
Input25
Output77
Input-40
Output-40
🧠

How to Think About It

To convert Celsius to Fahrenheit, multiply the Celsius temperature by 9, then divide by 5, and finally add 32. This formula changes the scale from Celsius to Fahrenheit by adjusting for the different zero points and unit sizes.
📐

Algorithm

1
Get the Celsius temperature input.
2
Multiply the Celsius value by 9.
3
Divide the result by 5.
4
Add 32 to the result.
5
Return or print the Fahrenheit temperature.
💻

Code

php
<?php
$celsius = 25;
$fahrenheit = ($celsius * 9 / 5) + 32;
echo "Temperature in Fahrenheit: " . $fahrenheit;
?>
Output
Temperature in Fahrenheit: 77
🔍

Dry Run

Let's trace converting 25 Celsius to Fahrenheit through the code

1

Input Celsius

Celsius value is 25

2

Multiply by 9

25 * 9 = 225

3

Divide by 5

225 / 5 = 45

4

Add 32

45 + 32 = 77

StepCalculationResult
Multiply by 925 * 9225
Divide by 5225 / 545
Add 3245 + 3277
💡

Why This Works

Step 1: Multiply Celsius by 9

This scales the Celsius value to match the Fahrenheit scale's unit size.

Step 2: Divide by 5

Dividing by 5 adjusts the scale ratio between Celsius and Fahrenheit.

Step 3: Add 32

Adding 32 shifts the zero point from Celsius to Fahrenheit.

🔄

Alternative Approaches

Using a function
php
<?php
function celsiusToFahrenheit(float $celsius): float {
    return ($celsius * 9 / 5) + 32;
}

echo celsiusToFahrenheit(25);
Encapsulates conversion in a reusable function for cleaner code.
Using round for integer output
php
<?php
$celsius = 25;
$fahrenheit = round(($celsius * 9 / 5) + 32);
echo $fahrenheit;
Rounds the result to nearest whole number for simpler display.

Complexity: O(1) time, O(1) space

Time Complexity

The calculation involves a fixed number of arithmetic operations, so it runs in constant time.

Space Complexity

Only a few variables are used, so the space needed is constant.

Which Approach is Fastest?

All approaches perform the same simple calculation, so they have identical performance; using a function improves code reuse but does not affect speed.

ApproachTimeSpaceBest For
Direct formulaO(1)O(1)Quick one-off conversions
Function encapsulationO(1)O(1)Reusable and clean code
Rounded outputO(1)O(1)User-friendly integer results
💡
Always use parentheses to ensure correct order of operations in the formula.
⚠️
Forgetting to add 32 after multiplying and dividing causes wrong Fahrenheit values.