7

Find First and Last Digits of a Number in PHP

 9 months ago
source link: https://www.geeksforgeeks.org/find-first-and-last-digits-of-a-number-in-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Find First and Last Digits of a Number in PHP

Discuss
Courses

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
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
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
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Last Updated : 12 Dec, 2023
Like Article
Save Article

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK