How to check if an integer include specific digits x times in PHP

1 Answer

0 votes
function checkDigitOccurrences($n, $xtims, $digit) {
    $count = 0;

    // Count occurrences of the digit in the number
    while ($n > 0) {
        if ($n % 10 == $digit) {
            $count++;
        }
        $n = intdiv($n, 10); // Use intdiv for integer division
    }

    // Return true if count matches xtims
    return $count == $xtims;
}

// Test the function with the given inputs
echo checkDigitOccurrences(7097175, 3, 7) ? 'true' : 'false';
echo "\n";
echo checkDigitOccurrences(70975, 3, 7) ? 'true' : 'false';



/*
run:

true
false

*/

 



answered Apr 26, 2025 by avibootz
...