Check Perfect Square in PHP

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Number Theory

What You’ll Learn

A perfect square equals k * k for some whole number k. Examples: 1, 4, 9, 16, 25. This tutorial covers the loop and (int)sqrt approaches, a live checker, worked PHP examples, edge cases, and complexity.

Definition

n = k²

Some integer k squares to n.

i*i Loop

Beginner

Try candidates while i*i <= n.

(int)sqrt

Robust

Integer root, then root*root == n.

0 and 1

Both square

0*0 and 1*1 both count.

Live Preview

Try 16 / 15

See k and the verdict instantly.

Not Perfect Number

Different idea

Squares vs divisor sums.

Introduction

A perfect square is a non-negative integer that equals some integer squared. So 16 is perfect because 4 * 4 = 16, while 15 is not because no whole k works.

Interviews usually accept either a clear i * i loop or a (int)sqrt check. Prefer integer roots over floating sqrt so large values stay exact.

Why it matters?

It is a classic math interview warm-up that teaches exact integer reasoning without float traps.

Key Highlights

n = k²

Some integer k squares to n.

Two Methods

Loop or (int)sqrt.

0 and 1

Both are perfect squares.

Avoid Float

Cast sqrt carefully for large n.

In short: find whether some integer k satisfies k * k == n.

📝 Problem & Approach

Given an integer n, decide whether it is a perfect square of a non-negative integer.

php
// 16 -> 4 * 4 = 16   perfect
// 15 -> no integer k  not perfect
// 0  -> 0 * 0 = 0    perfect
// 1  -> 1 * 1 = 1    perfect

Inputs & Outputs

ItemTypeDescription
n / numberintValue to test (non-negative for yes).
Returnbooltrue when some k has k*k == n.
Optional kintThe integer root when the answer is yes.

Minimal workflow

Pseudocode
function is_perfect_square_loop(n):
    if n < 0:
        return false
    i = 0
    while i * i <= n:
        if i * i == n:
            return true
        i = i + 1
    return false

Method comparison

MethodIdeaNotes
i*i loopTry candidates until square exceeds nClearest for beginners
(int)sqrt$root = (int)sqrt($n); $root * $root === $nFast and exact for integers
float sqrtround(sqrt(n))**2 == nRisky for large n — avoid

⚡ Quick Reference

GoalPattern
Reject negativesif ($n < 0) return false;
Loop checkfor ($i = 1; $i * $i <= $n; $i++)
Exact hitif ($i * $i === $n) return true;
sqrt cast check$root = (int)sqrt($n);
Verify rootreturn $root * $root === $n;
Build squares$k * $k for $k = 0, 1, 2, …

📋 Loop vs sqrt vs Float

Same question — different reliability.

i*i loop
$i * $i <= $n

Interview-friendly and exact

(int)sqrt
root*root == n

Preferred production check

float sqrt
avoid for ints

Rounding can lie on big n

vs perfect number
k*k vs s(n)=n

Different “perfect” meaning

Context

When This Problem Shows Up

Reach for a square check whenever you need exact integer roots.

  1. Interview warm-ups

    Simple math with an exactness twist.

  2. Grid / geometry puzzles

    Can n form a square layout?

  3. Filtering sequences

    Keep only square values in a range.

  4. Teaching sqrt cast

    Show why integer roots beat floats.

  5. Not for float domains

    This tutorial targets integer n.

Key benefit: one crisp boolean question that forces you to think in exact integers, not approximate roots.

🔮 Live Preview

Checks with integer logic, then reports the root and verdict.

Use whole numbers n >= 0.

Live result
Press “Run check” to see result.

Examples Gallery

Three complete PHP programs — loop check for 16, list squares from 1 to 50 with (int)sqrt, and generate squares by squaring. Click View Output to reveal sample console results.

📚 Getting Started

A beginner-friendly loop that never needs floating roots.

Example 1 — Integer Loop Check

Simple and beginner-friendly perfect square check.

php
<?php
function isPerfectSquare(int $number): bool
{
    if ($number < 0) {
        return false;
    }
    for ($i = 1; $i * $i <= $number; $i++) {
        if ($i * $i === $number) {
            return true;
        }
    }
    return $number === 0;
}

$testNumber = 16;
echo isPerfectSquare($testNumber)
    ? $testNumber . " is a perfect square.\n"
    : $testNumber . " is not a perfect square.\n";
?>

How It Works

Candidates advance while $i * $i has not passed 16. When $i reaches 4, the product matches and the function returns true. Zero is handled as a special case (0 = 0 * 0).

⚡ Square-Root Shortcut

Use sqrt() with an integer cast for a short check.

Example 2 — Range Scan Using sqrt

Use (int)sqrt() and print all perfect squares from 1 to 50.

php
<?php
function isPerfectSquare(int $num): bool
{
    if ($num < 0) {
        return false;
    }
    $root = (int)sqrt($num);
    return $root * $root === $num;
}

echo "Perfect Squares in the Range 1 to 50:\n";
for ($i = 1; $i <= 50; $i++) {
    if (isPerfectSquare($i)) {
        echo $i . " ";
    }
}
echo "\n";
?>

How It Works

(int)sqrt($num) truncates the floating square root toward zero. Squaring that root recovers $num exactly when $num is a perfect square.

Example 3 — Generate Squares by Squaring

Build squares directly instead of filtering every integer.

php
<?php
echo "First squares from k = 0 to 7:\n";
for ($k = 0; $k <= 7; $k++) {
    $square = $k * $k;
    echo $k . " * " . $k . " = " . $square . "\n";
}
?>

How It Works

When you only need the square sequence, squaring consecutive integers is cheaper than testing every n in a range.

🧠 How the Algorithm Decides

1

Reject negatives

No non-negative integer squares to a negative.

Guard
2

Find a candidate root

Loop i while i*i <= n, or call (int)sqrt(n).

Search
3

Compare square to n

Exact match means perfect square.

Rule
=

Return the verdict

true with root k, or false.

🔎 Worked Walkthrough — 16

Trace the loop method for n = 16.

ii * ii*i <= 16?Match?
00YesNo
11YesNo
24YesNo
39YesNo
416YesYes — return true

4 * 4 equals 16 — perfect square.

Use Cases

Where perfect-square checks show up beyond the interview prompt.

1. Interview Classics

Exact integer math checks.

Example: is_square(16).

2. Range Filtering

List squares inside a band.

Example: 1..50 list.

3. Sequence Generation

Build squares with k*k.

Example: Example 3.

4. Grid Layouts

Can n tiles form a square?

Example: 25 -> 5×5.

5. Teaching sqrt cast

Show exact integer roots.

Example: avoid float sqrt.

6. Next: Averages

Continue the interview chain.

Example: related CTA.

Pro Tip: say “I’ll check whether root*root equals n using an integer root” before coding.

Advantages

Why these approaches work well for beginners and interviews.

  1. 1. Easy to Trace

    Dry-run 16 on paper and watch i grow.

  2. 2. Exact Integers

    No float rounding surprises with sqrt cast.

  3. 3. Two Clear Styles

    Loop for clarity; sqrt cast for speed.

  4. 4. Generates Cleanly

    k*k builds the sequence without scanning.

Pro Tip: lead with the loop in interviews, then mention (int)sqrt as the robust alternative.

Usage Tips

Small habits that keep square checks interview-ready.

  1. 1. Guard Negatives

    Return false immediately for n < 0.

  2. 2. Prefer integer loop or careful cast

    Exact integer root for production code.

  3. 3. Verify root*root

    Never trust a root without squaring back.

  4. 4. Generate When Possible

    Use k*k if you need the sequence itself.

  5. 5. Separate From Perfect Number

    Name the definition so interviewers know you know.

Pro Tip: sanity-check 0, 1, 16, and 15 — if those four behave, your logic is solid.

Common Pitfalls

Mistakes that commonly break perfect-square programs.

  1. 1. Trusting float sqrt

    Large ints can round incorrectly.

    → Use (int)sqrt or an integer loop.

  2. 2. Skipping root verification

    Taking floor(sqrt) without squaring back.

    → Always compare root * root to n.

  3. 3. Confusing With Perfect Number

    Different “perfect” concept entirely.

    → This page is about k * k.

  4. 4. Forgetting 0

    Starting i at 1 and rejecting zero.

    → 0 = 0 * 0 is a square.

  5. 5. Accepting Negatives

    Returning true for -16 in real-integer checks.

    → Reject n < 0 in this tutorial.

Edge Cases

Handle these before claiming the check is complete.

n = 0

Zero is square

0 = 0 * 0.

n = 1

One is square

1 = 1 * 1.

Negative

Not a real integer square

Return false for negatives in this tutorial.

Large n

Avoid float precision

Prefer (int)sqrt over float sqrt.

15

Classic no

Between 9 and 16 — not square.

16

Classic yes

4 * 4 = 16.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Odd gaps. Differences between consecutive squares are odd: 3, 5, 7, 9…
  • Grid picture. n tiles form a square if and only if n is a perfect square.
  • sqrt cast identity. Perfect ⇔ (int)sqrt(n)² == n for n >= 0.
  • Name clash. Perfect square ≠ perfect number.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Prove 16

  • Trace the loop
  • Confirm 4 * 4

2. Reject 15

  • Show no matching i
  • (int)sqrt(15)=3, 9 != 15

3. List 1..50

  • Reproduce Example 2
  • Expect seven values

4. Generate k*k

  • Print first eight squares
  • Match Example 3

Notes

  • Definition: n is square if n = k * k.
  • Methods: integer loop or (int)sqrt.
  • Remember: 0 and 1 are perfect squares.
  • Cast sqrt to int and square back, or use the $i * $i loop for huge n. The loop takes O(sqrt(n)) checks. Return false immediately for negatives.

Quick Takeaway: n is a perfect square when some integer k satisfies k * k == n.

⏱️ Time and Space Complexity

ApproachTime (single n)Extra space
Loop until i*i > nO(sqrt(n))O(1)
sqrt cast-based checkO(1) practicalO(1)
Range 1..U scanO(U) checksO(1)

For interview demos, either method is fine; mention float pitfalls when asked about reliability.

Wrap Up

🎉 Conclusion

A perfect square equals some integer squared. Use an i * i loop or (int)sqrt, reject negatives, and remember that 0 and 1 count.

Practice the three examples above, then continue to finding the average of N numbers.

n = k² means perfect square; verify with integers, not float sqrt.

💡 Best Practices

✅ Do

  • Reject negatives early
  • Verify root * root == n
  • Prefer (int)sqrt for exactness
  • Treat 0 and 1 as squares
  • Generate with k*k when listing

❌ Don’t

  • Trust float sqrt alone
  • Skip squaring the root back
  • Confuse with perfect numbers
  • Forget zero as a square
  • Accept negatives as yes

Key Takeaways

Knowledge Unlocked

Five things to remember about perfect squares

Decide exact squares the interview-friendly way.

5
Core concepts
i 02

Loop

while i*i

Method
03

sqrt cast

root*root

Robust
0 04

Edges

0, 1 yes

Guards
O 05

Cost

O(√n)

Analysis

❓ Frequently Asked Questions

A whole number is a perfect square if it equals k * k for some whole number k.
Yes. 1 = 1 * 1.
The loop is easy to understand and avoids floating-point concerns.
It means we only test candidate roots whose square has not passed n.
Yes. Cast sqrt() to int, then square the root back and compare to n. For very large n the float sqrt can round wrong, so prefer the i*i loop or BCMath.
No. Perfect square is about k * k; perfect number is about divisor sums.
Yes. 0 = 0 * 0.
Large integers can round incorrectly. Squaring the truncated root back is the usual PHP check; for huge n use the i*i loop or BCMath.
About O(sqrt(n)) candidate checks for a single n.

Did you Know? 🔊

A perfect square is also a quadratic residue in everyday arithmetic: the count of objects you can arrange in a square grid with the same number of rows and columns. The gaps between consecutive squares 1, 4, 9, 16… grow by the odd numbers 3, 5, 7, 9…

Continue to Average of N Numbers

Learn how to find the average of N numbers in PHP.

Average 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.

9 people found this page helpful