# PHP: Built-In Functions

Aims:

• to learn how to use a few of PHP's built-in functions
• to learn how to make sense of the PHP manual

# Motivating example

• We wrote a program to convert RGB values using percentages to RGB values using decimal numbers between 0 and 255 inc.
• But the program isn't right
• Class exercise: What's wrong with it?

# Functions

• In PHP, a function is a named block of PHP that performs some task
• it takes in zero, one or more values (its actual parameters)
• it may return a value
• PHP has many built-in functions
• E.g. `sqrt` returns the positive square root of its actual parameter
• `sqrt(9)` returns 3

# The hypotenuse of a right-angled triangle

• Suppose `right_triangle.html` contains this form:
```<form action="hypotenuse.php" method="get">
<input type="text" name="c1" />
<input type="text" name="c2" />
<input type="submit" />
</form>```
• Write `hypotenuse.php`, which calculates the length of the hypotenuse of the right triangle, where the length of the sides adjacent to the right-angle are input into the form above
• Hypotenuse by Pythagoras' theorem

# More functions

• `abs(\$x)` returns the absolute value of `\$x`
• E.g. `abs(3)` returns 3
• E.g. `abs(-3)` returns 3
• `pow(\$x, \$y)` returns `\$x\$y`
• E.g. `pow(3, 4)` returns 81
• E.g. `pow(1000, 1/3)` returns 10
• Lots more: `sin`, `asin`, `asinh`,… even `hypot`!

# A key skill: reading the documentation

• In PHP documentation, functions are described by giving their prototype and some sentences of explanation
• E.g. the PHP manual: http://www.php.net/manual/en/
• The prototype specifies
• the return type
• the name of the function
• the type of each parameter
• Class exercise: What are the differences between using `(int)` and `floor`?

# A key skill: reading the documentation

• Some functions may have one or more optional actual parameters
• E.g.
• The square brackets indicate an optional parameter

# RGB conversions, again

• Modify `rgb_convert.php`, so it converts the percentages to the nearest decimal integer between 0 and 255 inc.