Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to print the number pattern
To print the number pattern in PHP, we use nested loops where each row contains the row number repeated row number of times. This creates a triangular pattern of numbers.
Example
<?php
function num_pattern($val)
{
$num = 1;
for ($m = 0; $m < $val; $m++)
{
for ($n = 0; $n <= $m; $n++ )
{
echo $num." ";
}
$num = $num + 1;
echo "<br>";
}
}
$val = 6;
num_pattern($val);
?>
Output
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6
How It Works
The function num_pattern() takes the limit as a parameter. The outer loop runs from 0 to the limit value, and the inner loop prints the current number ($num) for each position in that row. After printing each row, the number is incremented and a newline is added.
Alternative Pattern
Here's another variation that prints sequential numbers instead of repeating the same number ?
<?php
function sequential_pattern($val)
{
$num = 1;
for ($m = 0; $m < $val; $m++)
{
for ($n = 0; $n <= $m; $n++ )
{
echo $num." ";
$num++;
}
echo "<br>";
}
}
$val = 4;
sequential_pattern($val);
?>
1 2 3 4 5 6 7 8 9 10
Conclusion
Number patterns in PHP are created using nested loops, similar to star patterns but with numeric values. The outer loop controls rows while the inner loop handles printing numbers within each row.
