-
Notifications
You must be signed in to change notification settings - Fork 1
NumberInfo
The NumberInfo
class is a handy tool to work with numeric values in HTML and CSS: it handles the most common units, and allows numeric operations like adding and subtracting values.
The easiest way is to use the parseNumber()
function:
use function AppUtils\parseNumber;
$number = parseNumber('14px');
echo $number->getUnits();
This will output the following:
px
The parsing ignores all whitespace, and will convert numeric values with commas to valid numeric notation with dots.
The following numbers all give the same result:
parseNumber('15 px'); // 15px
parseNumber(' \t 15px \n '); // 15px
parseNumber('1,5em'); // 1.5em
Additions and subtractions work only of the units of the numbers are the same. No automatic conversions exist for adding pixels to percentages for example.
NOTE: Unitless numbers are assumed to be pixel values.
Operations between numbers of different units are silently ignored.
use function AppUtils\parseNumber;
$numberA = parseNumber('40px');
$numberB = parseNumber('10px');
$numberA->add($numberB);
echo $numberA->getNumber();
This will output the following result:
50
A number can easily be converted to the notation to use either in an HTML or CSS context.
In HTML attributes, only numbers or percentages are allowed. As a result, units are ignored if they are not a percentage. If the number has decimals, they are stripped.
use function AppUtils\parseNumber;
echo 'Percentage: '.parseNumber('500%')->toAttribute().PHP_EOL;
echo 'Pixel value: '.parseNumber('50px')->toAttribute().PHP_EOL;
echo 'Unitless number: '.parseNumber(44)->toAttribute().PHP_EOL;
echo 'Non HTML units: '.parseNumber('3.5em')->toAttribute();
This will show the following result:
Percentage: 500%
Pixel value: 50
Unitless number: 44
Non HTML units: 3
use function AppUtils\parseNumber;
echo 'EM Number: '.parseNumber('1.2em')->toCSS().PHP_EOL;
echo 'Percentage: '.parseNumber('50%')->toCSS().PHP_EOL;
echo 'Pixel value: '.parseNumber('120px')->toCSS().PHP_EOL;
echo 'Unitless number: '.parseNumber(120)->toCSS();
This will show the following output:
EM Number: 1.2em
Percentage: 50%
Pixel value: 120px
Unitless number: 120px
New here?
Have a look at the overview for a list of all helper classes available in the package.
Table of contents
Find the current page in the collapsible "Pages" list above, and expand the page, to view a table of contents.