In PHP, you can get the last digit of an integer in the following ways:
Using Modulo Operator
You can use the modulo operator (%
) to get the last digit of an integer in the following way:
function lastDigit(int $num): int { return $num % 10; } var_dump(lastDigit(0)); // 0 var_dump(lastDigit(1234)); // 4 var_dump(lastDigit(-1234)); // -4
In the example above, the modulo operator (%
) works by dividing a given number by 10
and returning the remainder. It uses truncated division, and is equivalent to the following:
function lastDigit(int $num): int { $quotient = intdiv($num, 10); return ($num - (10 * $quotient)); } var_dump(lastDigit(0)); // 0 var_dump(lastDigit(1234)); // 4 var_dump(lastDigit(-1234)); // -4
This works in the following way:
// num = 1234 // lastDigit = 1234 - (10 * intdiv(1234, 10)) // lastDigit = 1234 - (10 * 123) // lastDigit = 1234 - 1230 // lastDigit = 4
Converting to String and Returning Last Character
You could do the following:
- Convert the integer to a string;
- Get the last character of the string;
- Convert the string back to integer;
- Add negative sign to the last digit if integer was negative.
// PHP 7.1+ function lastDigit(int $num): int { $numStr = (string) $num; $lastChar = $numStr[-1]; $lastDigitUnsigned = (int) $lastChar; return ($num < 0) ? -$lastDigitUnsigned : $lastDigitUnsigned; } var_dump(lastDigit(0)); // 0 var_dump(lastDigit(1234)); // 4 var_dump(lastDigit(-1234)); // -4
To support versions prior to PHP 7.1, you can use $numStr[strlen($numStr) - 1]
instead of $numStr[-1]
.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.