Check Perfect Square in PHP

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code Examples
Number theory

What you’ll learn

  • What a perfect square is, with quick examples (1, 4, 9, 16…).
  • How to test a value with a loop that only uses integer multiplication i * i.
  • A second style using sqrt() to list squares in a range.
  • A live preview and the usual edge cases (zero, negatives, big numbers).

Overview

Pick a whole number n. If there is some whole number k with k × k = n, then n is a perfect square. The programs below answer “Is this n a square?” and “Which squares sit between 1 and 50?”

Two programs

Example 1 walks i until passes n. Example 2 uses sqrt and prints every square in [1, 50].

Live preview

Try values like 15, 16, or 1 before you compile anything.

Interview-ready

Know both the integer loop and the library square-root trick, plus why floats need care at huge scales.

Prerequisites

Comfortable with tiny PHP programs and the idea of multiplying a number by itself.

  • Basic PHP syntax, for loops, and integer comparisons.
  • For Example 2: basic sqrt() usage in PHP.
  • Basic squares: 1²=1, 2²=4, 3²=9, 4²=16.

What is a perfect square?

A perfect square (in arithmetic) is any whole number you get by squaring another whole number: n = k² for some integer k. Negative k does not create new values because (−k)² is the same as .

Non-examples help too: 2, 3, 5, 6, 7, 8 are not perfect squares. The next square after 9 is 16, so 10 through 15 sit between squares.

Quick examples

16 Square
Because
4 × 4 = 16
Verdict
Perfect square.
15 Not a square
Because
3² = 9 and 4² = 16; nothing in between.
Verdict
Not a perfect square.
1 Square
Because
1 × 1 = 1
Verdict
The smallest perfect square.

Live preview

Uses pure integer logic (no sqrt needed): find the smallest k with k² ≥ n, then check whether equals n.

Use whole numbers n ≥ 0. Very large values are capped so the tab stays responsive.

Live result
Press “Run check” to see whether n is a perfect square.

Algorithm

Goal: decide whether a nonnegative integer n equals for some integer k.

Loop version

Try i = 1, 2, 3, … until i * i > n. If any step has i * i == n, return success. If you finish without a hit, n is not a square.

sqrt version

Let r be the integer part of sqrt(n). If r * r == n, then n is a perfect square. Be cautious with floating rounding when n is enormous.

📜 Pseudocode

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

Integer loop (no math library)

Try successive integers i. Stop when would pass n. This matches the classic interview answer and needs only stdio.h.

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";
?>

Explanation

When i reaches 4, we get 4 * 4 == 16, so the function returns 1 (true). If n were 15, the loop would pass 3 * 3 and then 4 * 4 without equality and return 0.

2

Using sqrt and listing a range

Here sqrt() gives a floating root; casting to int truncates toward zero. For each i from 1 to 50, we test whether i is a square. The loop includes 1, since 1 = 1².

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";
?>

Explanation

int root = sqrt(num); return root * root == num;

Square-root shortcut. If truncating the square root and squaring again lands on num, then num is a perfect square.

for ($i = 1; $i <= 50; $i++) { if (isPerfectSquare($i)) echo $i . " "; }

Outer loop. Tests every integer in the interval; only squares print. Change 50 to scan a different window.

Notes

Linking. PHP has sqrt() built in, so no separate math-linking flag is needed.

Floating limits. For very large n, sqrt in floating point can round wrong. Prefer the integer loop or wide integer libraries when n approaches 1012 and beyond.

Overflow. In the loop, i * i can overflow a 32-bit int if i grows too far; use a wider type or stop when i > n / i style checks are needed.

❓ FAQ

A whole number is a perfect square if you can write it as another whole number times itself. For example, 9 is a perfect square because 3 &times; 3 = 9.
Yes. It equals 1 &times; 1. Some old puzzle pages word this badly; the usual math answer is that 1 is a perfect square.
A small loop is easy to reason about and never calls the math library. The sqrt form is short and fast; just watch floating rounding on very large integers (use integer methods or wide types for huge n).
As i grows, i&sup2; grows. You can stop the loop as soon as i&sup2; would pass the target. If you never hit i&sup2; = number, it is not a perfect square.
No. PHP provides sqrt() directly, so you can use it without compiler flags.
No. A perfect number is about sums of divisors (see the perfect number tutorial). A perfect square is about being an exact square of an integer.

🔄 Input / output examples

Example 1 uses a fixed $testNumber. Replace it or read with trim(fgets(STDIN)) in PHP CLI for interactive runs.

ValueTypical line (Example 1)
1616 is a perfect square.
1515 is not a perfect square.
11 is a perfect square.
00 is a perfect square. (if you extend the test for zero)

Edge cases

These keep answers tidy in exams and code reviews.

n = 0

Zero

0 = 0 × 0, so zero is a perfect square if your problem allows nonnegative integers. The loop for (i = 1; …) never runs for n = 0, so treat 0 as a special case if you need it.

Negative

No real integer square

Negative integers are not perfect squares of real integers. Return false immediately if the assignment restricts to nonnegative n.

sqrt

Rounding

Always compare by squaring the truncated root again, as in root * root == num. Never trust a bare floating equality against n without that check.

⏱️ Time and space complexity

ApproachTime (single n)Extra space
Loop until i² > nO(√n)O(1)
sqrt onceO(1) typical math costO(1)
List squares in [1, U]O(U) testsO(1)

Summary

  • Idea: n is a perfect square when n = k² for some integer k.
  • Code: loop with i * i, or take sqrt and verify by squaring the truncated root.
  • Watch: avoid overflow on i * i for huge values, and remember 1 is a square.
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…

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