How can I separate a number and get the first two digits in PHP?

one possibility would be to use substr:

echo substr($mynumber, 0, 2);

EDIT:
please not that, like hakre said, this will break for negative numbers or small numbers with decimal places. his solution is the better one, as he's doing some checks to avoid this.


First of all you need to normalize your number, because not all numbers in PHP consist of digits only. You might be looking for an integer number:

$number = (int) $number;

Problems you can run in here is the range of integer numbers in PHP or rounding issues, see Integers Docs, INF comes to mind as well.

As the number now is an integer, you can use it in string context and extract the first two characters which will be the first two digits if the number is not negative. If the number is negative, the sign needs to be preserved:

$twoDigits = substr($number, 0, $number < 0 ? 3 : 2);

See the Demo.

Tags:

Php