Star Cross Pattern with 0s in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Conditions

What You’ll Learn

The star cross pattern fills a grid with 0s and prints * on the main diagonal, anti-diagonal, and middle column. This tutorial covers the three conditions, nested loops, live preview, algorithm steps, worked PHP examples, edge cases, and complexity.

Shape Rule

Three conditions

Print * when $i==$j, $j==$mid, or $i==$cols+1-$j; otherwise print 0.

Column Loop

$j = 1..$cols

for ($j = 1; $j <= $cols; $j++) walks every column in the current row.

Cross Check

mid column

$mid = intdiv($cols, 2) + 1 locates the center column when $cols is odd (e.g. 9 → 5).

Outer Loop

Row index i

for ($i = 1; $i <= $rows; $i++) walks each row of the rectangular grid.

Live Preview

1–12 rows

Pick a row count and draw the star cross pattern instantly in the browser (columns fixed at 9).

O($rows×$cols)

Complexity

Visits every cell once — $rows×$cols iterations; extra memory stays O(1).

Introduction

A star cross pattern with 0s prints * on the main diagonal, anti-diagonal, and middle column; every other cell prints 0. With $rows = 4 and $cols = 9, the last row becomes 000***000.

In PHP you use nested loops ($i = 1..$rows, $j = 1..$cols) and a three-part if that picks * or 0 for each cell.

Why it matters?

It combines diagonal math with a center-column check — a classic grid pattern after number diamonds.

Key Highlights

Main Diagonal

$i == $j draws the top-left to bottom-right line.

Anti-Diagonal

$i == $cols + 1 - $j completes the X shape.

Middle Column

$j == $mid adds the vertical line through the center.

Series Foundation

Follow Program 44 number diamond; continue to Program 46 concentric square.

In short: nested row/column loops, three-part if for *, else 0; call echo PHP_EOL after each row.

📝 Problem & Approach

Given $rows = 4 and $cols = 9, print a grid where * marks the X and middle column; all other cells are 0.

PHP
// $rows = 4, $cols = 9 (conceptual shape)
// *000*000*
// 0*00*00*0
// 00*0*0*00
// 000***000

Inputs & Outputs

ItemTypeDescription
$rowsintNumber of rows in the grid (typically ≥ 1).
$colsintNumber of columns (9 in the classic example; odd width gives one center column).
Printed outputtextrows × cols characters — * on cross lines, 0 elsewhere.

Minimal workflow

Pseudocode
$mid = intdiv($cols, 2) + 1
for $i from 1 to $rows:
    for $j from 1 to $cols:
        if $i==$j or $j==$mid or $i==$cols+1-$j: print *
        else: print 0
    print newline

Approach comparison

ApproachIdeaBest for
Three-condition grid*000*000* first row with X + mid columnLearning and interviews
User-input rowstrim(fgets(STDIN)) with fixed $cols = 9Flexible console programs
X-only crossDrop $j == $mid — diagonals onlyContrast with full cross

⚡ Quick Reference

GoalPattern
Walk rowsfor ($i = 1; $i <= $rows; $i++)
Walk columnsfor ($j = 1; $j <= $cols; $j++)
Cross if$i==$j || $j==$mid || $i==$cols+1-$j
Center column$mid = intdiv($cols, 2) + 1
End the rowecho PHP_EOL;
Program 44 contrastNumber diamond uses mirrored rows; this pattern uses a fixed grid with diagonal checks

📋 Diagonal vs Middle vs Combined

Same grid cell — how the three cross conditions pick * or 0.

Cross check
$i == $j

Main diagonal — top-left to bottom-right

Anti-diagonal
i == $cols+1-$j

Secondary diagonal for the X shape

Middle column
$j == $mid

Vertical line through center ($mid = intdiv($cols, 2)+1)

Learning tip
trace i=2,j=5

Dry-run cell (2,5): mid column → prints *

Context

When This Pattern Shows Up

Reach for this pattern when teaching diagonal conditions inside a full row×column grid.

  1. First lab exercise

    Classic follow-up after diamonds and symbol grids.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with fgets(STDIN) for a flexible row count.

  4. Gateway to variants

    Compare with Program 44 (number diamond), then continue to Program 46 (concentric square).

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O($rows×$cols) thinking.

🔮 Live Preview

Choose a row count (columns fixed at 9) and draw the star cross pattern in the browser.

Columns stay at 9. Try 3, 4, or 6 rows (up to 12).

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed row count, fgets(STDIN) input, and an X-only cross variant. Click View Output to reveal sample console results.

📚 Getting Started

Print four rows over nine columns with nested loops and a three-part if.

Example 1 — Fixed $rows = 4, $cols = 9

Hard-coded size — nested loops and the cross check build each row.

PHP
<?php
$rows = 4;
$cols = 9;
$mid = intdiv($cols, 2) + 1;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $cols; $j++) {
        if ($i == $j || $j == $mid || $i == $cols + 1 - $j) {
            echo "*";
        } else {
            echo "0";
        }
    }
    echo PHP_EOL;
}

How It Works

When $i = 1, $j = 1, the main-diagonal check prints *. When $i = 2, $j = 5, the middle-column check prints * while neighbors print 0.

📈 Practical Variant

Let the user choose the row count at runtime (columns stay at 9).

Example 2 — User Input Version

Read the row count with trim(fgets(STDIN)) (check is_numeric($input) in real apps).

PHP
<?php
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input)) {
    echo "Invalid input." . PHP_EOL;
    exit(1);
}
$rows = (int) $input;
$cols = 9;
$mid = intdiv($cols, 2) + 1;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $cols; $j++) {
        if ($i == $j || $j == $mid || $i == $cols + 1 - $j) {
            echo "*";
        } else {
            echo "0";
        }
    }
    echo PHP_EOL;
}

How It Works

Same nested-loop core as Example 1; only the source of $rows changes. Non-numeric input fails is_numeric($input) — validate before casting to int for safer labs.

⚡ Readability Variant

Remove the middle-column check for a plain X without the vertical center line.

Example 3 — X-Only Cross

Remove the middle-column check to print a plain X without the vertical center line.

PHP
<?php
$rows = 4;
$cols = 9;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $cols; $j++) {
        if ($i == $j || $i == $cols + 1 - $j) {
            echo "*";
        } else {
            echo "0";
        }
    }
    echo PHP_EOL;
}

How It Works

Same nested-loop grid; dropping $j == $mid leaves only the two diagonals that form the X.

🧠 How the Algorithm Prints Rows

1

Set up

echo is built in; use fgets(STDIN) when reading input. Set $rows, $cols = 9, and $mid = intdiv($cols, 2) + 1.

Setup
2

Outer loop (rows)

for ($i = 1; $i <= $rows; $i++) — walks each row of the grid.

Row
3

Inner loop (columns)

for ($j = 1; $j <= $cols; $j++) visits every column in the current row.

Column
4

Inner loop + if

Three checks print *; else 0, then echo PHP_EOL ends the row.

Cells
=

Star cross pattern with 0s complete

Total cell visits equal $rows×$colsO($rows×$cols) time, O(1) extra memory.

🔎 Worked Walkthrough — cell $i = 2, $j = 5

Trace one center-column cell to see the three checks in action.

CheckResultPrints
$i == $j (2==5)false
$j == $mid (5==5)true*
i == $cols+1-$j (2==5)false

Cell output: * — full grid visits: 4×9 = 36 = $rows×$cols.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: drop $j == $mid and get an X-only cross instead.

2. Pattern Series Base

Foundation for symbol grids, diagonal patterns, and cross variants.

Example: swap * and 0 for 1 and 0 to build a number cross.

3. Console Formatting Drills

Practice echo vs row newline without complex math.

Example: put echo PHP_EOL inside the inner loop by mistake.

4. Character Substitution

Swap * and 0 for other symbols once the loop works.

Example: replace * with 1 and keep 0 as fill.

5. Complexity Intuition

Grid totals make O($rows×$cols) concrete for beginners.

Example: count cells for rows=4, cols=9 → 36 visits.

6. Input Validation Labs

Pair the pattern with fgets(STDIN) and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner PHP courses.

  1. 1. Instant Visual Feedback

    Wrong diagonal formulas show up immediately as a broken or shifted X.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Drop the middle column, swap symbols, or change column width with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the three-condition grid first; then try the X-only cross in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use $rows (or n) and keep i/j for row/column — or rename to row/col.

  2. 2. Prefer fgets(STDIN)

    Avoid crashes when the user types letters instead of a number.

  3. 3. Keep echo PHP_EOL Outside

    Only call echo PHP_EOL after the inner loop finishes the row.

  4. 4. Use Ternary for Compact Code

    Compact if: echo ($i==$j||$j==$mid||$i==$cols+1-$j ? "*" : "0"); inside the inner loop.

  5. 5. Dry-Run One Small n

    Trace $rows = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of characters per line, you almost certainly put echo PHP_EOL inside the inner loop.

Common Pitfalls

Mistakes that commonly break star cross patterns.

  1. 1. echo PHP_EOL Inside the Inner Loop

    Each character lands on its own line — you get a column, not a grid row.

    → Use echo for each cell; echo PHP_EOL only after the inner loop finishes.

  2. 2. Wrong Anti-Diagonal Formula

    Using i + j == cols instead of $i == $cols + 1 - $j shifts the secondary diagonal.

    → Keep $i == $cols + 1 - $j for cols=9 (e.g. row 2, col 8 → 2==2).

  3. 3. Forgetting the Row Break

    Omitting echo PHP_EOL glues every row onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked fgets(STDIN) input

    Letters or empty input leave $rows unset.

    → Use is_numeric($input) and re-prompt on failure.

  5. 5. Forgetting mid

    Computing $mid after the loops or using even $cols without adjusting center logic.

    → Set $mid = intdiv($cols, 2) + 1 once before the loops; prefer odd column counts.

Edge Cases

Check these inputs before calling the solution done.

$rows = 1

Single row

Output is one row of nine characters following the same three checks.

$rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Many rows

Output grows as $rows*$cols cell visits plus spaces — fine for labs, noisy for huge n.

Bad input

Non-numeric fgets(STDIN) input

Unchecked fgets(STDIN) leaves $rows unset — call is_numeric($input) first.

X-only

Drop middle column

Remove $j == $mid for a plain X — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change column width

  • Try $cols = 7 or $cols = 11 and observe $mid
  • Keep the same three checks

2. Number cross

  • Replace * with 1 and keep 0 as fill
  • Same nested-loop structure

3. X-only variant

  • Remove $j == $mid like Example 3
  • Compare output side by side

4. Next in series

  • Continue with Program 46 concentric square
  • Read rows and cols from input

Notes

  • Cell count. Total characters printed = $rows×$cols (e.g. 4×9 = 36).
  • echo stays on the line; echo PHP_EOL advances — mix them carefully.
  • Validate $rows > 0 for interactive programs; $rows = 1 prints one cross row.
  • Use odd $cols so $mid points to one clear center column; even widths split the center.

Quick Takeaway: compute $mid, loop rows and columns, three-part if for *, else 0, then break the row.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O($rows×$cols)O(1)
X-only cross (Example 3)O($rows×$cols)O(1)
Wrap Up

🎉 Conclusion

The star cross pattern with 0s combines nested loops with a simple grid fill pattern — a natural step after number diamonds. Master the fixed-$rows version first, then try user input and the X-only cross in Example 3.

Practice the three examples above, then continue to Program 46 for the concentric number square pattern.

Every cell uses print — keep echo PHP_EOL only after the inner column loop finishes.

💡 Best Practices

✅ Do

  • Explain main diagonal, anti-diagonal, and mid column before coding
  • Use print("*") or print("0") and echo PHP_EOL after each row
  • Validate $rows ≥ 1 for interactive programs
  • Check fgets(STDIN) return value before using $rows
  • State O($rows×$cols) time when asked about complexity

❌ Don’t

  • Call echo PHP_EOL inside the inner column loop
  • Forget $mid = intdiv($cols, 2) + 1 before the loops
  • Use i + j == cols instead of $i == $cols + 1 - $j
  • Ignore bad console input in user-facing demos
  • Skip the $rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this star cross pattern with 0s

Print the pattern the beginner-friendly way.

5
Core concepts
02

Cross check

Three-part if

Code
03

Anti-diagonal

$i==$cols+1-$j

Logic
n 04

Grid size

$rows×$cols

I/O
O 05

Complexity

O($rows×$cols)

Analysis

❓ Frequently Asked Questions

It draws an X (both diagonals) and a vertical middle line using *. All other positions are filled with 0.
Because the pattern uses 9 columns, and $mid = intdiv($cols, 2) + 1 = 5. For an odd column count, there is a single center column.
For $cols=9, the anti-diagonal satisfies $i == $cols+1-$j (equivalently $i == 10-$j).
On row $i=4, the diagonals hit columns 4 and 6, and the middle column is 5 — three adjacent * characters in the center.
Yes. Delete the condition $j == $mid. Keep only $i == $j and $i == $cols+1-$j — see Example 3.
It works best with an odd number of columns so there is a single middle column. Even columns change the center behavior.
O($rows*$cols) because the nested loops visit each cell once.
Use trim(fgets(STDIN)) and is_numeric($input) before casting to int.

Did you Know? 🔊

A * prints on the main diagonal ($i==$j), anti-diagonal ($i==$cols+1-$j), and middle column ($j==$mid). Every other cell prints 0.

Continue to Program 46

Move on to the concentric number square pattern in the PHP number-pattern series.

Program 46 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.

12 people found this page helpful