# 30 seconds of PHP

## Math

Click on a snippet's name to view its code.

#### approximatelyEqual

Checks if two numbers are approximately equal to each other.

Use `abs()`

to compare the absolute difference of the two values to `$epsilon`

.
Omit the third parameter, `$epsilon`

, to use a default value of `0.001`

.

#### average

Returns the average of two or more numbers.

Use `array_sum()`

for all the values in `$items`

and return the result divided by their `count()`

.

#### clampNumber

Clamps `$num`

within the inclusive range specified by the boundary values `$a`

and `$b`

.

If `$num`

falls within the range, return `$num`

.
Otherwise, return the nearest number in the range, using `min()`

and `max()`

.

#### factorial

Calculates the factorial of a number.

Use recursion.
If `$n`

is less then or equal to `1`

, return `1`

.
Otherwise, return the product of `$n`

and the factorial of `$n -1`

.
Throws an exception if `$n`

is a negative number.

#### fibonacci

Generates an array, containing the Fibonacci sequence, up until the nth term.

Create an empty array, initializing the first two values (`0`

and `1`

).
Loop from 2 through `$n`

and add values into the array, using the sum of the last two values.

#### gcd

Calculates the greatest common divisor between two or more numbers.

Use recursion.
Use `array_reduce()`

with the `gcd`

function to appy to all elements in the `$numbers`

list.
Base case is when `y`

equals `0`

. In this case, return `x`

.
Otherwise, return the gcd of `y`

and the remainder of the division `x/y`

.

#### isEven

Returns `true`

if the given number is even, `false`

otherwise.

Checks whether a number is odd or even using the modulo (`%`

) operator.
Returns `true`

if the number is even, `false`

if the number is odd.

#### isPrime

Checks if the provided integer is a prime number.

Check numbers from `2`

to the square root of the given number.
Return `false`

if any of them divides the given number, else return `true`

, unless the number is less than `2`

.

#### lcm

Returns the least common multiple of two or more numbers.

Use the greatest common divisor (GCD) formula and the fact that `lcm(x,y) = x * y / gcd(x,y)`

to determine the least common multiple.
The GCD formula uses recursion.

#### maxN

Returns the maximum value from the provided array.

Use `array_filter()`

and `max()`

to find the maximum value in an array.

#### median

Returns the median of an array of numbers.

Find the middle of the array, use `sort()`

to sort the values.
Return the number at the midpoint if the array's length is odd, otherwise the average of the two middle numbers.

#### minN

Returns the minimum value from the provided array.

Use `array_filter()`

and `min()`

to find the minimum value in an array.