Check Palindrome Number in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digit reversal

What You’ll Learn

A palindrome number reads the same forward and backward — like 121 or 9009. This tutorial covers digit reversal with % 10 and / 10, range listing, a string alternative, a live preview, worked PHP examples, edge cases, and complexity.

Definition

Same both ways

Digits match when read left-to-right and right-to-left.

Reverse Digits

% 10 / 10

Peel the last digit and rebuild the flipped number.

Compare

rev == original

Equality finishes the classic interview check.

Range Scan

100..200

Print every three-digit palindrome in the band.

Live Preview

Try 121

Check nonnegative integers in the browser.

O(d) Cost

d digits

One pass over the digits; ranges multiply that cost.

Introduction

A palindrome number has decimal digits that read the same forward and backward. Think of 121: front to back is “1-2-1,” and back to front is the same.

The classic interview approach peels off the last digit repeatedly, builds the reversed number, and checks equality with the original. Single-digit values like 7 or 0 always pass.

Why it matters?

It is a staple loop drill: modulo, integer division, and careful handling of trailing zeros and negatives.

Key Highlights

Save Original

You mutate a working copy while reversing.

Digit Loop

rev = rev * 10 + n % 10

Single Digits

Always palindromes for nonnegative n.

Trailing Zeros

120 reverses to 21 — not a palindrome.

In short: reverse the digits of a nonnegative integer and compare with the saved original — equality means palindrome.

📝 Problem & Approach

Given a nonnegative integer, decide whether its decimal digits form a palindrome. Optionally list all palindromes in a closed range.

php
// 121 -> reverse 121 -> palindrome
// 123 -> reverse 321 -> not a palindrome
// 120 -> reverse 21  -> not a palindrome

Inputs & Outputs

ItemTypeDescription
$numberintNonnegative integer to classify.
Returnbooltrue if digits form a palindrome.
Printed outputtextYes/no sentence, or listed values in a range.

Minimal workflow

Pseudocode
function isPalindrome(n):
    original = n
    reversed = 0
    while n != 0:
        reversed = reversed * 10 + (n mod 10)
        n = floor(n / 10)
    return original == reversed

Method comparison

MethodIdeaNotes
Digit reverseBuild rev with % / 10Interview default — O(d) time, O(1) space
String two endsCompare chars from both sidesAvoids overflow; uses O(d) string space
Half reverseReverse only half the digitsLeetCode-style optimization

⚡ Quick Reference

GoalPattern
Last digit$digit = $n % 10;
Drop last digit$n = (int)($n / 10);
Append to reverse$rev = $rev * 10 + $digit;
Comparereturn $original === $rev;
Range filterif (isPalindrome($i)) echo $i . " ";
String check$s === strrev($s)

📋 Digit Reverse vs String vs Half Reverse

Same answer — different costs and interview signals.

Digit reverse
% / 10 loop

This page — classic O(1) extra space

String
strrev

Simple; watch memory and leading zeros

Half reverse
stop mid-way

Fewer multiplies for large values

Interview tip
mention 120

Trailing zeros break integer reverse

Context

When This Problem Shows Up

Reach for digit reversal whenever you must test mirror symmetry of an integer.

  1. Interview warm-ups

    Loops, modulo, and equality checks.

  2. Before string palindromes

    Same idea with characters instead of digits.

  3. Range generation

    List all palindromes in a band for demos.

  4. Teaching digit math

    Practice % 10 and integer division.

  5. Not for signed inputs alone

    Define a policy for negatives before coding.

Key benefit: one short loop that locks in digit extraction, reversal, and edge talk about zeros.

🔮 Live Preview

Enter a nonnegative integer (same convention as the PHP samples). Reverses digits the same way as Example 1.

Try 121, 123, 0, or 7. Negative input is rejected here.

Live result
Press “Check palindrome.”

Examples Gallery

Three complete PHP programs — reverse-and-compare for 121, palindromes from 100 to 200, and a string two-pointer check. Click View Output to reveal sample console results.

📚 Getting Started

Classic reverse-digits helper with sample 121.

Example 1 — Check One Number

Classic interview structure: 121 reads 121 backward too.

php
<?php
function isPalindrome(int $number): bool
{
    $originalNumber = $number;
    $reversedNumber = 0;

    while ($number != 0) {
        $remainder = $number % 10;
        $reversedNumber = $reversedNumber * 10 + $remainder;
        $number = (int)($number / 10);
    }

    return $originalNumber === $reversedNumber;
}

$number = 121;

if (isPalindrome($number)) {
    echo $number . " is a palindrome number.\n";
} else {
    echo $number . " is not a palindrome number.\n";
}
?>

How It Works

The loop strips digits from $number until it becomes 0. $reversedNumber accumulates the flipped version; comparing with $originalNumber finishes the test.

⚡ Scan a Range

Reuse the helper to list every hit in a closed band.

Example 2 — Palindromes from 100 to 200

Three-digit palindromes in this band look like aba: hundreds digit equals units digit.

php
<?php
function isPalindrome(int $num): bool
{
    $originalNum = $num;
    $reversedNum = 0;

    while ($num != 0) {
        $remainder = $num % 10;
        $reversedNum = $reversedNum * 10 + $remainder;
        $num = (int)($num / 10);
    }

    return $originalNum === $reversedNum;
}

echo "Palindrome numbers in the range 100 to 200:\n";

for ($i = 100; $i <= 200; $i++) {
    if (isPalindrome($i)) {
        echo $i . " ";
    }
}

echo "\n";
?>

How It Works

Same helper as Example 1; the outer for walks every candidate in the inclusive range and prints hits.

⚙️ String Alternative

Compare characters from both ends — no arithmetic reverse.

Example 3 — String Two-Pointer Check

Convert to a string and walk inward from both ends. Useful when overflow is a concern.

php
<?php
function isPalindromeString(int $number): bool
{
    if ($number < 0) {
        return false;
    }

    $s = (string)$number;
    $left = 0;
    $right = strlen($s) - 1;

    while ($left < $right) {
        if ($s[$left] !== $s[$right]) {
            return false;
        }
        $left++;
        $right--;
    }

    return true;
}

$number = 12321;
echo $number . (isPalindromeString($number) ? " is a palindrome number.\n" : " is not a palindrome number.\n");
?>

How It Works

Indices $left and $right move toward the middle; any mismatched pair fails immediately. This uses O(d) string space but never multiplies a growing reverse integer.

🧠 How the Algorithm Reverses Digits

1

Remember original

Save $original before mutating the working copy.

Setup
2

Peel and append

Take % 10, append to $rev, then integer-divide by 10.

Loop
3

Compare

If $rev === $original, it is a palindrome.

Decide
=

Verdict ready

Return true or false (or print a clear sentence).

🔎 Worked Walkthrough — Reverse 121

Trace the digit loop for Example 1.

StepWorking $nDigit$rev
Start1210
11211
21212
301121

Final: 121 === 121 — palindrome.

Use Cases

Where integer palindrome checks show up beyond the interview prompt.

1. Interview Warm-Ups

Digit loops and equality.

Example: write isPalindrome($n).

2. Range Listing

Print all hits in a closed band.

Example: 100..200 scan.

3. Teaching % and /

Last digit and drop-last patterns.

Example: peel 121 step by step.

4. Before String Palindromes

Same mirror idea with characters.

Example: Example 3 pattern.

5. Overflow Talk

Huge reverses may need strings.

Example: mention int limits.

6. Trailing-Zero Edge

Explain why 120 fails as an integer.

Example: 120 → 21.

Pro Tip: open with “save original, reverse with % and /, compare” before writing the loop.

Advantages

Why digit-reversal earns interview points.

  1. 1. Constant Extra Space

    Only a few integers — no array of digits required.

  2. 2. Easy to Trace

    Dry-run 121 on paper and watch rev grow.

  3. 3. Reusable Helper

    Drop isPalindrome into any range scan.

  4. 4. Clear Complexity

    O(d) in the number of digits.

Pro Tip: lead with digit reverse; mention the string approach as a overflow-safe alternative.

Usage Tips

Small habits that keep palindrome solutions interview-ready.

  1. 1. Save the Original

    Never compare after you have zeroed the working copy without a backup.

  2. 2. Cast Integer Division

    Use (int)($n / 10) so PHP stays on whole digits.

  3. 3. Clarify Negatives

    State whether negatives are rejected or handled specially.

  4. 4. Test Trailing Zeros

    Dry-run 10 and 120 so you remember leading zeros vanish.

  5. 5. Mention Overflow

    For huge values, discuss string comparison as a backup.

Pro Tip: dry-run 121 → rev 1, 12, 121 aloud before coding — if that matches, the update formula is correct.

Common Pitfalls

Mistakes that commonly break palindrome-number solutions.

  1. 1. Forgetting to Save Original

    Comparing after the working value is already 0.

    → Store $original before the loop.

  2. 2. Float Division

    Using / without casting can leave fractions.

    → Use (int)($n / 10) (or intdiv).

  3. 3. Ignoring Trailing Zeros

    Expecting 120 to reverse to 021.

    → Integers drop leading zeros; 120 → 21.

  4. 4. Negatives Without a Policy

    Feeding signed values into unsigned digit logic.

    → Reject or handle signs explicitly.

  5. 5. Overflow on Huge Reverses

    Growing $rev * 10 past platform limits.

    → Use a string check or discuss big integers.

Edge Cases

Handle these before calling the check done.

Trailing zeros

120 vs 21

Integer reversal drops trailing zeros on the right (they become leading zeros). So 120 reverses to 21.

Single digit

n < 10

Always palindromes for nonnegative n.

Zero

n = 0

One digit — palindrome.

Negatives

Signed input

These samples assume nonnegative; reject or define a rule.

Even length

1221

Works the same — reverse still equals original.

Large n

Overflow risk

Consider string comparison if reverse may overflow.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Single digits. Every nonnegative n with fewer than two digits is a palindrome.
  • Form aba. Three-digit palindromes have equal hundreds and units digits.
  • Digits matter. Palindrome is a property of decimal spelling, not of the abstract integer alone (leading zeros).
  • Words too. The same mirror idea appears in string palindrome problems.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Dry-run 121

  • Trace rev through 1, 12, 121
  • Confirm equality

2. Fail cases

  • Check 123 and 120
  • Explain each reverse

3. Range 200..300

  • Reuse Example 2 bounds
  • Expect 202, 212, …, 292

4. String version

  • Implement Example 3
  • Compare results with digit reverse

Notes

  • Core trick: reverse digits with % 10 and / 10, compare to the saved original.
  • Ranges: reuse isPalindrome inside a for loop.
  • Watch-outs: overflow on huge values; negatives need a separate plan.
  • Alternatives: string two-pointer checks avoid arithmetic overflow.

Quick Takeaway: reverse digits, compare to original — and remember trailing zeros break integer reverse.

⏱️ Time and Space Complexity

OperationTimeExtra space
isPalindrome(n) digit reverseO(d) digitsO(1)
String two-pointerO(d)O(d) for the string
Range [a, b]O((b-a+1) · d)O(1)

For positive integers, d is about floor(log10 n) + 1.

Wrap Up

🎉 Conclusion

Checking a palindrome number is digit reversal plus equality: save the original, rebuild with % 10 and / 10, and compare. Reuse the helper for ranges, and keep string comparison ready when overflow or negatives need a clearer story.

Practice the three examples above, then continue to Pascal’s triangle.

Save original, reverse digits, compare — and dry-run 120 so trailing zeros do not surprise you.

💡 Best Practices

✅ Do

  • Save the original before reversing
  • Use integer division for digit peeling
  • Test 0, single digits, and 120
  • State a policy for negatives
  • Mention O(d) time / O(1) space for digit reverse

❌ Don’t

  • Compare after destroying the original
  • Assume 120 reverses to 021
  • Ignore overflow on huge reverses
  • Feed negatives without a plan
  • Skip inclusive bounds on range scans

Key Takeaways

Knowledge Unlocked

Five things to remember about palindrome numbers

Check digit mirrors the interview-friendly way.

5
Core concepts
= 02

Compare

rev == original

Rule
7 03

Short

1 digit OK

Edge
0 04

Zeros

120 fails

Edge
O 05

Cost

O(d) / O(1)

Analysis

❓ Frequently Asked Questions

Write the digits on paper. Read them left-to-right and right-to-left. If both readings are the same (like 121 or 9009), the number is a palindrome.
Rebuilding the number backward gives you something easy to compare with the original using ==. That is the classic loop interview solution.
Yes. Digits like 3 or 8 read the same forward and backward.
Yes. It has one digit and reads the same either way.
These snippets assume nonnegative integers. Negatives need extra care because stripping digits with % behaves differently with signs in PHP.
Reversing an n-digit number costs O(number of digits), roughly O(log10 value) for positive integers. Scanning a range multiplies by how many integers you test.
Integer reversal of 120 becomes 21 because leading zeros disappear. Digits 1-2-0 do not match 0-2-1 as integers.
Yes. Convert to a string and compare characters from both ends. It avoids arithmetic overflow but uses extra memory.

Did you Know? 🔊

The word palindrome also describes words like “radar” or “level”—for integers we only compare digits, so single-digit numbers like 7 always pass.

Continue to Pascal’s Triangle

Learn how to generate Pascal’s triangle rows with nested loops in PHP.

Pascal’s triangle tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful