I need to get the units of a two-digit number with PHP.
example:
$num = 25;
$dig1 = 2;
$dig2 = 5;
I need to get the units of a two-digit number with PHP.
example:
$num = 25;
$dig1 = 2;
$dig2 = 5;
To get the unit, just calculate the rest of the division by 10:
$num = 25;
echo $num % 10; // Imprime 5
And for the decade, just take the whole part of the division by 10:
$num = 25;
echo intdiv($num, 10); // Imprime 2
The same works for negative values:
$num = -25;
echo intdiv($num, 10) . PHP_EOL; // Imprime -2
echo $num % 10 . PHP_EOL; // Imprime -5
See working at Ideone .
Since the intdiv
function was only introduced in PHP version 7, an alternative to PHP 5 is to use the round
function:
echo round($num/10, 0, PHP_ROUND_HALF_DOWN);
The first value refers to the value to be rounded; the second refers to the number of decimal places and the third if the same should be rounded down. This would return 2 for $num = 25
and -2 for $num = -25
.
In the php all string can be considered an array of characters and it is possible to cast an int to string, so you can get the digits of a number like
In PHP 7
$num = 25;
$dig1 = ((string)abs($num))[0];
$dig2 = ((string)abs($num))[1];
In PHP > = 5.4
$num = 25;
$dig1 = strval(abs($num))[0];
$dig2 = strval(abs($num))[1];
Divide by 10 and take the rest of the division.
$num = 25;
$unidades = 25 % 10; // retorna 5
You can use the php str_split () function
$array = str_split($num);