How to use Logarithm In PHP

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

Find First and Last Digits of a Number in PHP

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:

 

Table of Content

  • Using Loop
  • Using Logarithm
  • Using str_split() Function

Similar Reads

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....

Using Logarithm

...

Using str_split() Function

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)....