How to check if specific digit exists in a number with PHP

2 Answers

0 votes
function check_digit_exists($n, $digit) {
    while ($n > 0) {
        if ($digit == $n % 10) {
            return true;
        }
        $n = (int)($n / 10);
    }
    
    return false;
}

$num = 230138;

echo check_digit_exists($num, 2) ? "true\n" : "false\n";

echo check_digit_exists($num, 5) ? "true\n" : "false\n";





/*
run:

true
false

*/

 



answered Oct 3, 2023 by avibootz
0 votes
$num = 230138;

echo strpos((string)$num, '1') ? "true\n" : "false\n";

echo strpos((string)$num, '5') ? "true\n" : "false\n";




/*
run:

true
false

*/

 



answered Oct 4, 2023 by avibootz

Related questions

2 answers 152 views
1 answer 123 views
2 answers 155 views
2 answers 145 views
2 answers 133 views
...