Temperature Conversion

Main Lab 5 Page


In some cases, when the same operation is being done over and over again, a loop may not be appropriate. The circumstances can change quite drastically, or happen infrequently. So a loop just simply wouldn't work. In these cases, a user-defined function can come in quite handy. (”User“ in this case referring to the user of PHP, not the user of the website.)

A function can be used in a variety of cases. For instance, if one is calculating the conversion for Celsius to Fahrenheit. The calculation is always the same, only with different values. In these cases, a function can be written that does the calculation. This will reduce the number of typos, since it always calls the same line of code over and over again. And for more complex functions, it'll save space and make revision all the more easier, since changes only have to be made once.

Functions operate in the same way they do in other languages. As such, they can contain whatever code the writer may want, including if statements and for loops. They can also be called any number of times, with any sort of data. As long as the function is defined before it's used.

The table below utilizes the same loop from the last example. But this time, the calculation from Celsius to Fahrenheit is done within a function. Does this make things more efficient? Well, no not in this case, since the calculation is so simple, and it exists in a loop anyway. but it's just a simple demonstration, and it works. However, this design would allow the temperature conversion to used quite easily outside the loop, were it to become necessary, without the writer having to re-enter the formula.

Celsius Fahrenheit
-40°-40°
-30°-22°
-20°-4°
-10°14°
32°
10°50°
20°68°
30°86°
40°104°
50°122°
60°140°
70°158°
80°176°
90°194°
100°212°