Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to extract the last N digits from a number in PHP

1 Answer

0 votes
/*
    Extracts the last N digits from a given number.

    Approach:
      - To get the last N digits, compute: number % (10 ** digits)
      - This avoids string manipulation and uses efficient arithmetic.

    Parameters:
      $number : the original integer
      $digits : how many digits to extract from the end

    Returns:
      The last N digits as an integer.
*/
function getLastNDigits(int $number, int $digits): int
{
    // Compute 10^digits using PHP's exponent operator (**)
    $divisor = 10 ** $digits;

    // Modulo returns the remainder, which is exactly the last N digits
    return $number % $divisor;
}

// Example values
$number = 987654321;
$digits = 4;

// Extract the last N digits
$result = getLastNDigits($number, $digits);

// Display the result
echo "Original number: $number\n";
echo "Digits requested: $digits\n";
echo "Last $digits digits: $result\n";



/*
run:

Original number: 987654321
Digits requested: 4
Last 4 digits: 4321

*/

 



answered 2 days ago by avibootz
...