PHP Pattern Programs

Pattern NamePattern Short DescriptionPattern PHP CodeResult
Pyramid repeated1. Define the Number of Rows – The pyramid will have 5 rows.

2. Outer Loop – Controls the Rows. – Runs 5 times ($d = 0 to $d = 4), each iteration corresponds to one row.

3. Printing Leading Spaces – The number of spaces decreases as rows go down.

4. Printing Left Side Numbers (Increasing Order) – Prints numbers from 0 to ($d + 1).

5. Printing Right Side Numbers (Decreasing Order) – Prints numbers from $d down to 1 to create a symmetric pattern.

6. Moving to the Next Line echo “<br>”; Moves to the next row.
$cn = 5;
for($d=0; $d<$cn; $d++){
// Print leading spaces
for($g=0; $g < $cn – $d – 1; $g ++){
echo “&nbsp&nbsp”;
}
// Print left side numbers (increasing order)
for($g = 0; $g <= $d + 1; $g++){
echo $g;
}
// Print right side numbers (decreasing order)
for ($g = $d; $g > 0; $g–) {
echo $g;
}
echo “<br>”; // Move to next line
}
01
0121
012321
01234321
0123454321
Inverted triangle1. The number of spaces increases as we move down the rows.

2. The number of digits per row decreases as we go downward.

3. Each row prints the same digit repeatedly.
$nn = 4; //This sets the variable $nn to 4, which determines the number of rows in the pattern.

for($df = 0; $df <= $nn; $df++){
//This loop controls the number of rows in the pattern.
//$df starts from 0 and goes up to $nn (4).
for($j=0; $j<$df; $j++){
echo ” “;
}
//This loop prints spaces before the numbers.
//The number of spaces increases as the rows go down.
for($j=0; $j<$nn – $df; $j++){
echo ($df + 1);
}
//This loop prints numbers.
//The number of digits per row decreases as we move downward.
//The number displayed is (df + 1), meaning the first row prints 1, the second row prints 2, etc.
echo PHP_EOL;
//Moves to the next line for the next row.
}
1111
222
33
4
Reverse triangle1. The outer loop ($ss) runs from 0 to 4 (total 5 rows).

2. The inner loop ($sd) starts from $ss + 1 and counts down to 1, printing the numbers in reverse.
$n = 5;

for($ss=0; $ss<$n; $ss++){
for($sd=$ss + 1; $sd>0; $sd–){
echo $sd;
}
echo PHP_EOL;
}
1
21
321
4321
54321
Floyd triangle character1. The outer loop ($ss) runs from 0 to 3 (total 4 rows).

2. The inner loop ($j) runs from 0 to $ss, printing characters increasingly.

3. The variable $num starts from ‘A’ and increments sequentially.
$vv = 4;
$num = ‘A’; // Initialize the starting character as ‘A’
for ($ss = 0; $ss < $vv; $ss++) {
for ($j = 0; $j < $ss + 1; $j++) {
echo $num; // Print the character
$num++; // Increment to the next character
}
echo PHP_EOL; // Move to the next line
}
A
BC
DEF
GHIJ
Floyd triangle1. The outer loop ($ss) controls the number of rows (4 rows).

2. The inner loop ($j) prints incrementing numbers in each row.

3. $num starts from 1 and increments continuously across all rows.
$vv = 4;
$num = 1;
for ($ss = 0; $ss < $vv; $ss++) {
for ($j = 0; $j < $ss + 1; $j++) {
echo $num; // Print the number
$num++; // Increment to the next number
}
echo PHP_EOL; // Move to the next line
}
1
23
456
78910
Right-angled triangle pattern with sequential numbers1. The outer loop ($aa) runs from 1 to 4 ($c - 1 = 5, but the condition is $aa < 5, so it stops at 4).

2. The inner loop ($sd) runs from 1 to $aa, printing numbers in increasing order for each row.
$c = 6;
for ($aa = 1; $aa < $c – 1; $aa++) {
for ($sd = 1; $sd < $aa + 1; $sd++) {
echo $sd; // Print numbers incrementally
}
echo “\n”; // Move to the next line
}
1
12
123
1234
Triangle pattern of increasing characters1. The outer loop ($dd) controls the number of rows (4 rows).

2. The inner loop ($tt) prints characters in increasing quantity for each row.

3. $char starts as ‘A’ and increments after each row.
$ff = 4;
$char = ‘A’;
for ($dd = 0; $dd < $ff; $dd++) {
for ($tt = 0; $tt < $dd + 1; $tt++) {
echo $char; // Print the current character
}
$char++; // Move to the next character in the alphabet
echo “\n”; // Move to the next line
}
A
BB
CCC
DDDD
Square pattern where characters are continuously increasing row-wise1. The outer loop ($jd) controls the number of rows (3 rows).

2. The inner loop ($jds) prints 3 characters per row.

3.$char starts as ‘A’ and increments sequentially across rows.
$ns = 3;
$char = ‘A’;
for ($jd = 1; $jd <= $ns; $jd++) { for ($jds = 1; $jds <= $ns; $jds++) { echo $char; // Print the current character $char++; // Move to the next character in the alphabet } echo ‘
‘; // Move to the next line (for HTML output)
}
ABC
DEF
GHI
Solid Square Pattern1. The outer loop ($q) runs 4 times, controlling the number of rows.

2. The inner loop ($j) runs 4 times per row, printing * symbols in a square formation.

3 .Each row contains 4 asterisks (*), and there are 4 rows in total.
$n = 4;
for ($q = 1; $q <= $n; $q++) { for ($j = 1; $j <= $n; $j++) { echo ‘*’; // Print an asterisk } echo ‘
‘; // Move to the next line (for HTML output)
}
****
****
****
****
Straight Sequence Pattern1.The loop runs 6 times (from 1 to 6).

2. Each iteration prints a single character.

3.$char starts as ‘A’ and increments with each iteration.

4. There is no line break, so all characters are printed in a single line.
$ns = 6;
$char = ‘A’;
for ($jd = 1; $jd <= $ns; $jd++) {
echo $char; // Print the current character
$char++; // Move to the next character in the alphabet
}
ABCDEF
Square Number Pattern1. Defines the number of rows and columns (3×3 grid)

2. Initializes the counter variable.

3. Stores current value (not used in printing)

4. Increments the number

5. Prints the incremented number.
$n = 3;
$num = 0;
for($v=0; $v<$n; $v++){
for($j = 0; $j < $n; $j++){
$count = $num;
$num++;
echo $num;
}
echo'<br>’;
}
123
456
789
Right Rotation (Cyclic Rotation) of an ArrayEdge Case Handling:
If the array is empty or $K is a multiple of count($A), return the array as is (no rotation needed).
Normalize K:
If $K > n, rotating the array $K times is the same as rotating it $K % n times.
Manual Array Rotation:
First, we take the last $K elements and move them to the front.
Then, we shift the first n-K elements to the right positions.
No extra loops, just two simple loops.
function solutions($A, $K) {
$n = count($A);
// Handle edge cases if ($n == 0 || $K % $n == 0) { return $A; // No rotation needed } // Normalize K (If K > n, we only need to rotate K % n times) $K = $K % $n; // Manual rotation $newArray = []; // Move last K elements to the beginning for ($i = 0; $i < $K; $i++) { $newArray[$i] = $A[$n - $K + $i]; } // Move first n-K elements to the remaining positions for ($i = 0; $i < $n - $K; $i++) { $newArray[$K + $i] = $A[$i]; } return $newArray;
}
// Example Usage:
$A = [5, 3, 6, 55, 77, 33, 2]; $K = 1;
$solution = solutions($A, $K);
print_r($solution);

OUTPUT
Array
(
[0] => 2
[1] => 5
[2] => 3
[3] => 6
[4] => 55
[5] => 77
[6] => 33
)
Bubble Sort algorithm in an ascending orderWe declare an unsorted array.
count($array) is used to get the number of elements dynamically.
The outer loop runs from the first element to the second-last element.
($n - 1) ensures that we don’t go beyond the last element.
The inner loop starts from i + 1 and iterates through the unsorted portion of the array.
It compares the current element ($array[$i]) with the rest of the elements ($array[$j]).
If the current element ($array[$i]) is greater than the next element ($array[$j]), they are swapped.
The temporary variable $tmp is used to hold the value during the swap.
$array = [3, 4, 2, 1, 5, 6, 8, 7, 9, 4];
$n = count($array); // Get dynamic length of array
for ($i = 0; $i < $n – 1; $i++) { for ($j = $i + 1; $j < $n; $j++) { if ($array[$i] > $array[$j]) {
// Swap elements
$tmp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $tmp;
}
}
}
print_r($array);
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
)
FactorialThis code calculates the factorial of a given number using a loop.
Initialize Variables
$num = 5; → The number for which we need to find the factorial.
$fact = 1; → Stores the result of the factorial calculation.
Loop to Multiply Numbers
for ($g = $num; $g > 0; $g--)
The loop starts from $num (5) and decrements down to 1.
Multiplies $fact by the current value of $g in each iteration.
Multiplication Logic
First iteration: fact = 1 * 5 = 5
Second iteration: fact = 5 * 4 = 20
Third iteration: fact = 20 * 3 = 60
Fourth iteration: fact = 60 * 2 = 120
Fifth iteration: fact = 120 * 1 = 120
Print the Final Factorial Value
print_r($fact); → Displays the result, which is 120 for 5!
$num = 5;
$fact = 1;
for($g=$num; $g>0; $g–){
$fact = $fact * $g;
}
print_r($fact);
120
Fibonacci series

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones.
How It Works (Step-by-Step)
Start with 0 and 1.
Print the first number ($n1).
Compute the next number: $next = $n1 + $n2.
Update values:$n1 = $n2
$n2 = $next
Repeat for 15 iterations.
$limit = 15;
$n1 = 0;
$n2 = 1;
for($i = 0; $i < $limit; $i++){ echo $n1 . “
“; // Print current Fibonacci number
$next = $n1 + $n2; // Compute the next term
$n1 = $n2; // Shift numbers
$n2 = $next; // Update for next iteration
}
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
Is number is Prime.Handling Small Values ($num <= 1)
Prime numbers are greater than 1, so 0 and 1 are not prime.

Loop Runs Until sqrt($num) Instead of $num
Instead of looping up to $num, we loop only up to sqrt($num).
Optimization: If a number has a divisor greater than its square root, it must also have a corresponding divisor smaller than the square root.

Checking for Divisibility ($num % $i == 0)
If $num is divisible by any number between 2 and sqrt($num), it’s not a prime.

Returning true if No Factors Were Found
If no divisor is found, the number is prime.
function isPrime($num) {
if ($num <= 1) return false;
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}

// Example usage:
$num = 29; // Change this value to check for another number

if (isPrime($num)) {
echo “$num is a prime number.”;
} else {
echo “$num is not a prime number.”;
}

29 is a prime number.
Binary Search CodebinarySearch() is a function that takes a sorted array and an element to search.
If the element is found, it returns the index; otherwise, it returns -1.
$start = 0Starting index of the array.
$end = count($array) - 1Last index of the array.
The loop continues searching until the start index exceeds the end index.
($start + $end) / 2 → Finds the middle index.
floor() → Ensures it is a whole number (integer).
If the middle element matches the search element, return the index.
If the middle element is smaller, the element must be in the right half.
Update $start = $mid + 1.
If the loop exits without finding the element, return -1.
function binarySearch($array, $element) {
$start = 0;
$end = count($array) – 1;
while ($start <= $end) { $mid = floor(($start + $end) / 2); if ($array[$mid] === $element) { return $mid; // Found, return index } elseif ($array[$mid] < $element) { $start = $mid + 1; // Search right half } else { $end = $mid - 1; // Search left half } } return -1; // Not found
}
$number = [3, 6, 8, 10, 44, 56, 58, 89, 90, 100, 300];
$result = binarySearch($number, 58);
if ($result !== -1) {
echo “Element found at index: ” . $result;
} else {
echo “Element not found”;
}
Techinfo Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *