How to find the digit next to a given digit in a number with PHP

1 Answer

0 votes
class DigitFinder
{
    /**
     * Finds the digit that comes after the target digit when scanning from right to left.
     *
     * @param int $number The number to search within.
     * @param int $target The digit to find.
     * @return int The digit that comes after the target, or -1 if not found or no next digit.
     */
    public static function findNextDigit(int $number, int $target): int {
        $next = -1;

        while ($number > 0) {
            $current = $number % 10;
            $number = intdiv($number, 10);

            if ($current === $target) {
                return $next;
            }

            $next = $current;
        }

        return -1;
    }
}

$number = 8902741;
$target = 2;

$result = DigitFinder::findNextDigit($number, $target);

if ($result !== -1) {
    echo "The digit after {$target} in {$number} is {$result}." . PHP_EOL;
} else {
    echo "The digit {$target} is not found or has no next digit in {$number}." . PHP_EOL;
}



/*
run:

The digit after 2 in 8902741 is 7.

*/

 



answered Oct 18, 2025 by avibootz
...