Triangular Multiplication Pattern in PHP

What You’ll Learn
How to print a triangular multiplication pattern in PHP using two nested for loops.
Each row i displays products from i*1 to i*i, giving a multiplication-based number triangle.
⭐ Pattern Output
For rows 1 through 10, the pattern looks like this:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
10 20 30 40 50 60 70 80 90 100Complete PHP Program
The outer loop picks the row number, and the inner loop prints the row’s multiplication sequence.
<?php
for ($i = 1; $i <= 10; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo ($j * $i) . " ";
}
echo PHP_EOL;
}🧠 How It Works
Outer loop (rows)
for ($i = 1; $i <= 10; $i++) controls row number and table base.
Inner loop (columns)
for ($j = 1; $j <= $i; $j++) prints exactly i values in row i.
Multiplication value
Each cell prints $j * $i, producing row-wise multiples of $i.
Move to next line
echo PHP_EOL; starts a new row after each inner loop.
Triangular multiplication table
Total terms are 1+2+...+n = n(n+1)/2, so time complexity is O(n²).
Variation — User Input (CLI) Version
This version asks the user for number of rows (run from terminal with php):
<?php
echo "Enter number of rows: ";
$rows = (int) trim(fgets(STDIN));
if ($rows < 1) {
echo "Rows must be at least 1" . PHP_EOL;
exit;
}
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo ($j * $i) . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Align columns with
str_pad()for cleaner table look - Print reverse triangle by counting rows downward
- Export rows into arrays for further calculations
- Add color/styling when rendering in HTML context
- Change formula (e.g.,
$i + $j,$i - $j) for new patterns
Avoid
- Wrapping each value in HTML tags in CLI-focused output
- Skipping input validation for row count
- Forgetting newline after each row
- Mixing row and column loop bounds accidentally
Key Takeaways
Outer loop decides row number and multiplier base.
Inner loop prints values from i*1 to i*i.
Total printed values follow triangular count n(n+1)/2.
The same nested-loop shape works for many other numeric formulas.
❓ Frequently Asked Questions
$j <= $i. For $i = 5, it prints $j = 1..5.Explore More PHP Number Patterns!
Keep sharpening nested-loop skills with more sequence and table patterns.
Triangular multiplication patterns are a practical way to visualize both multiplication tables and triangular-number growth in one exercise.
12 people found this page helpful
