Open In App

Find First and Last Digits of a Number in PHP

Last Updated : 12 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Number, the task is to find the first, and last digits of a number using PHP.

Examples:

Input: num = 145677
Output: First Digit: 1, and Last Digit: 7
Input: 101130
Output: First Digit: 1, and Last Digit: 0

There are three methods to get the first and last digit of number, these are:

 

Using Loop

In this section, we use while loop to get the first and last digit of number. Remainder operator is used to get the last digit of number, and for first digit, use while loop.

PHP
<?php

function firstAndLastDigits($number) {
    $lastDigit = $number % 10;
    
    while ($number >= 10) {
        $number = (int)($number / 10);
    }
    
    $firstDigit = $number;
    
    return [$firstDigit, $lastDigit];
}

$num = 12345;
list($firstDigit, $lastDigit) = firstAndLastDigits($num);

echo "First Digit: $firstDigit, Last Digit: $lastDigit";

?>

Output
First Digit: 1, Last Digit: 5

Using Logarithm

Here, we use Logarithm to get the first digit of number. To get the first digit, divide the number by 10 power length of given number i.e. $number / pow(10, $len).

Example:

PHP
<?php

function firstAndLastDigits($number) {
    $len = floor(log10($number));
    $firstDigit = (int)($number / pow(10, $len));
    $lastDigit = $number % 10;
    return [$firstDigit, $lastDigit];
}

$num = 12345;
list($firstDigit, $lastDigit) = firstAndLastDigits($num);

echo "First Digit: $firstDigit, Last Digit: $lastDigit";

?>

Output
First Digit: 1, Last Digit: 5

Using str_split() Function

In this section, first, we convert the number of string and then split into an array, then get the first and last element of array.

PHP
<?php

function firstAndLastDigits($number) {
    $arr = str_split((string)$number);
    
    $firstDigit = $arr[0];
    $lastDigit = $arr[sizeof($arr)-1];
    return [$firstDigit, $lastDigit];
}

$num = 12345;
list($firstDigit, $lastDigit) = firstAndLastDigits($num);

echo "First Digit: $firstDigit, Last Digit: $lastDigit";

?>

Output
First Digit: 1, Last Digit: 5

Similar Reads