Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Numbers and maths

Prices, percentages, ratings, sizes — almost every program computes something. PHP has a set of ready-made functions for that.

Rounding

round() rounds to the nearest value. The second argument is the number of decimal places:

<?php
 
echo round(4.6), "\n";        // 5
echo round(3.14159, 2), "\n"; // 3.14
echo round(1250, -2);         // 1300

A negative precision rounds to tens and hundreds.

Up and down

floor() rounds down, ceil() rounds up. intdiv() divides without a remainder:

<?php
 
echo floor(4.7), "\n";   // 4
echo ceil(4.2), "\n";    // 5
echo intdiv(17, 5), "\n"; // 3
echo 17 % 5;             // 2

ceil() is handy for pagination: ceil(45 / 10) gives five pages for 45 records.

Largest, smallest, absolute value

<?php
 
echo max(3, 9, 5), "\n";    // 9
echo min([3, 9, 5]), "\n";  // 3
echo abs(-7), "\n";         // 7
echo 2 ** 10, "\n";         // 1024
echo sqrt(81);              // 9

max() and min() accept both separate numbers and an array.

Formatting

number_format() turns a number into a string for showing to the user: it sets the number of decimals, the decimal point and the thousands separator:

<?php
 
echo number_format(1234567.891), "\n";            // 1,234,568
echo number_format(1234567.891, 2), "\n";         // 1,234,567.89
echo number_format(1234567.891, 2, ',', ' ');     // 1 234 567,89

The result is a string. You cannot compute with it further, so format the number at the very end, when printing.

Random numbers

random_int() returns a random integer within the given bounds, both included:

<?php
 
$dice = random_int(1, 6);
 
echo $dice >= 1 && $dice <= 6 ? 'The dice was rolled' : 'Error';

random_int() is suitable for passwords and confirmation codes too. array_rand() gives a random element of an array, and shuffle() shuffles an array.

Checking that a value is a number

Form data arrives as strings. is_numeric() checks whether a string looks like a number:

<?php
 
var_dump(is_numeric('42'));   // bool(true)
var_dump(is_numeric('4.5'));  // bool(true)
var_dump(is_numeric('4 kg')); // bool(false)

Common mistake

Fractional numbers are stored in binary and are not always exact. The sum 0.1 + 0.2 differs from 0.3 by a tiny amount, so comparing with == gives false:

<?php
 
var_dump(0.1 + 0.2 == 0.3);                // bool(false)
var_dump(abs(0.1 + 0.2 - 0.3) < 0.00001);  // bool(true)
var_dump(round(0.1 + 0.2, 2) == 0.3);      // bool(true)

Compare fractions with a tolerance or after rounding. Money is more reliably stored as a whole number of cents.

Thanks for reading!

Donate to the site — we work hard for you.