A Harshad number (also called a Niven number) is a positive integer that is divisible by the sum of its digits.
Remember
n is Harshad ⇔ n % digitSum(n) == 0
(and digitSum(n) ≠ 0)
Example: 18
digit sum = 1 + 8 = 9
18 % 9 = 0 → Harshad
Example: 11
digit sum = 1 + 1 = 2
11 % 2 ≠ 0 → not Harshad
n
Digit sum
n % sum
Harshad?
18
9
0
Yes
12
3
0
Yes
11
2
1
No
7
7
0
Yes
Approach
How to Check a Harshad Number in PHP
Four clear steps — sum the digits, then test divisibility.
Work with a positive value (reject $n <= 0 for the standard definition).
Compute the sum of decimal digits with % 10 and intdiv($n, 10).
Guard against a digit sum of 0 (avoid modulus by zero).
Return true when $n % $digitSum === 0.
Method
Idea
Time
Best for
Digit peel
% 10 / intdiv, then modulus
O(log n)
Interviews, no strings
String digits
Sum chars from (string) $n, then modulus
O(log n)
Readable alternate style
Pseudocode
Pseudocode
function IsHarshad(n):
if n <= 0:
return false
sum = 0
temp = n
while temp > 0:
sum = sum + (temp mod 10)
temp = floor(temp / 10)
if sum == 0:
return false
return (n mod sum) == 0
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Definition
$n % digitSum($n) === 0
Also called
Niven number
1–9
All are Harshad
Zero
Not used in the standard positive definition
Digit sum
Peel with % 10 and intdiv(..., 10)
Classic check
18 → yes; 11 → no
Try it
Live Preview
Enter a positive integer to see the digit sum and whether it is Harshad.
Positive whole numbers. Tap a chip or type a value.
Result
n = 18
Digit sum = 1 + 8 = 9
18 % 9 = 0
Verdict: HARSHAD NUMBER
Trace
Worked Walkthrough — n = 18
Sum the digits, then ask whether 18 divides evenly by that sum.
Calculation
temp = 18, sum = 0
18 % 10 = 8 → sum = 8, temp = 1
1 % 10 = 1 → sum = 9, temp = 0
digitSum = 9
18 % 9 = 0 ✓
Result: 18 is a Harshad number
Code
PHP Programs
Start with the classic digit-peel check. Then use a string digit sum when you want a more readable alternate.
Example 1 — Digit Peel
Sum digits with % 10 / intdiv, then test $n % $sum === 0.
PHP
<?php
function isHarshad(int $n): bool {
if ($n <= 0) {
return false;
}
$sum = 0;
$temp = $n;
while ($temp > 0) {
$sum += $temp % 10;
$temp = intdiv($temp, 10);
}
return $sum !== 0 && $n % $sum === 0;
}
$number = 18;
if (isHarshad($number)) {
echo $number . " is a Harshad number\n";
} else {
echo $number . " is not a Harshad number\n";
}
?>
Output
18 is a Harshad number
How It Works
Reject non-positive $n for the standard definition.
Copy $n into $temp so the original value stays available for the final modulus.
Peel each digit with $temp % 10 and shrink with intdiv($temp, 10).
For 18: sum becomes 9, then 18 % 9 === 0.
Require $sum !== 0 so you never modulus by zero.
Example 2 — String Digit Sum
Cast to a string, add each digit character, then apply the same divisibility test.