Shifting Odd Number Pattern in PHP

What You’ll Learn
How to print a shifting odd-number pattern in PHP where each next row starts from the next odd number: 13579, 3579, 579, 79, 9.
You’ll practice nested loops with a step size of 2 to iterate through odd numbers only.
⭐ Pattern Output
For odd numbers up to 9, the pattern looks like this:
13579
3579
579
79
9Complete PHP Program
The outer loop picks the starting odd number. The inner loop prints odd numbers from that start up to the maximum odd value.
<?php
$maxOdd = 9;
for ($i = 1; $i <= $maxOdd; $i += 2) {
for ($j = $i; $j <= $maxOdd; $j += 2) {
echo $j;
}
echo PHP_EOL;
}🧠 How It Works
Choose the max odd number
$maxOdd = 9; sets the last number printed in each row.
Outer loop (starting odd)
for ($i = 1; $i <= $maxOdd; $i += 2) picks the first number of each row: 1, 3, 5, 7, 9.
Inner loop (print remaining odds)
for ($j = $i; $j <= $maxOdd; $j += 2) prints odd numbers from the current start up to $maxOdd.
New line per row
echo PHP_EOL; moves to the next line after each row.
Shifted odd-number rows
Each row starts later, so fewer numbers are printed: 5 digits, then 4, 3, 2, and 1.
Variation — User Input (CLI) Version
Let the user choose the maximum odd number at runtime (run from terminal with php):
<?php
echo "Enter the maximum odd number (e.g., 9): ";
$maxOdd = (int) trim(fgets(STDIN));
if ($maxOdd < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
if ($maxOdd % 2 === 0) {
$maxOdd -= 1; // adjust to the nearest lower odd number
}
for ($i = 1; $i <= $maxOdd; $i += 2) {
for ($j = $i; $j <= $maxOdd; $j += 2) {
echo $j;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Print spaces between numbers for readability on larger max values
- Start from a different first odd (like 3) to shift the triangle
- Reverse the pattern by printing from the max odd down to the start
- Replace odds with even numbers by starting at 2 and stepping by 2
- Validate CLI input and auto-adjust even numbers to odd
Avoid
- Using a max value of 0 or negative without validation
- Forgetting the newline after each row
- Mixing step sizes (both loops should step by 2 for odds)
- Assuming user input is already odd in CLI mode
Key Takeaways
Use step size 2 to iterate only over odd numbers.
The outer loop selects the start of each row.
The inner loop prints from the start odd up to the max odd.
Auto-adjusting even input to odd makes the CLI version more user-friendly.
❓ Frequently Asked Questions
2, so they visit only odd values: 1, 3, 5, 7, 9.$maxOdd = 15 (or read it from input). Keep += 2 in both loops.2 and step by 2 (2, 4, 6, ...). Also set the max to an even number.Explore More PHP Number Patterns!
Practice step-size loops and shifting starts—they show up in many number and matrix problems.
Loop step sizes (like += 2) are a simple way to iterate through filtered sequences—odd numbers, even numbers, or every k-th element.
12 people found this page helpful
