Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to check if all digits of a number divide it
To check if all digits of a number divide it in PHP, we extract each digit and verify if it divides the original number without remainder. Zero digits are handled separately since division by zero is undefined.
Example
Here's a complete program to check if all digits of a number divide it −
<?php
function divisibility_check($my_val, $my_digit)
{
return ($my_digit != 0 && $my_val % $my_digit == 0);
}
function divide_digits($my_val)
{
$temp = $my_val;
while ($temp > 0)
{
$my_digit = $temp % 10;
if (!(divisibility_check($my_val, $my_digit)))
return false;
$temp = intval($temp / 10);
}
return true;
}
$val = 128;
if (divide_digits($val))
echo "All digits divide the number $val";
else
echo "Not all digits divide the number $val";
?>
All digits divide the number 128
How It Works
The divisibility_check() function verifies two conditions: the digit is not zero (to avoid division by zero) and the original number is completely divisible by the digit. The divide_digits() function extracts each digit using modulo operation and checks divisibility for each digit.
Testing Different Numbers
<?php
function divisibility_check($my_val, $my_digit)
{
return ($my_digit != 0 && $my_val % $my_digit == 0);
}
function divide_digits($my_val)
{
$temp = $my_val;
while ($temp > 0)
{
$my_digit = $temp % 10;
if (!(divisibility_check($my_val, $my_digit)))
return false;
$temp = intval($temp / 10);
}
return true;
}
$numbers = [128, 102, 36, 24];
foreach($numbers as $num) {
if (divide_digits($num))
echo "$num: All digits divide the number<br>";
else
echo "$num: Not all digits divide the number<br>";
}
?>
128: All digits divide the number 102: Not all digits divide the number 36: All digits divide the number 24: All digits divide the number
Conclusion
This algorithm efficiently checks digit divisibility by extracting each digit and testing if it divides the original number. It properly handles zero digits by skipping division by zero checks.
