your image

PHP Alphabet Triangle Program using Methods - javatpoint

javapoint
Related Topic
:- PHP

Alphabet Triangle Method

There are three methods to print the alphabets in a triangle or in a pyramid form.

  • range() with for loop
  • chr() with for loop
  • range() with foreach loop

Logic:

  • Two for loops are used.
  • First for loop set conditions to print 1 to 5 rows.
  • Second for loop set conditions in decreasing order.

Using range() function

This range function stores values in an array from A to Z. here, we use two for loops.

Example:

 

1. Build a CMS using OOP PHP tutorial | PHP MVC design pattern [2020]

  1. <?php  
  2. $alpha = range('A', 'Z');  
  3. for($i=0; $i<5; $i++){   
  4.   for($j=5; $j>$i; $j--){  
  5.     echo $alpha[$i];  
  6.     }  
  7.     echo "<br>";  
  8. }  
  9. ?>  

Output:

Using chr() function

Here the chr() function returns the value of the ASCII code. The ASCII value of A, B, C, D, E is 65, 66, 67, 68, 69 respectively. Here, also we use two for loops.

Example:

  1. <?php  
  2. for( $i=65; $i<=69; $i++){   
  3.    for($j=5; $j>=$i-64; $j--){  
  4.     echo chr($i);  
  5.     }  
  6.     echo "<br>";  
  7. }  
  8. ?>  

Output:

Using range() function with foreach

In this methods we use foreach loop with range() function. The range() function contain values in an array and returns it with $char variable. The for loop is used to print the output.

Example:

  1. <?php  
  2. $k=1;  
  3. foreach(range('A','Z') as $char){  
  4.     for($i=5; $i>=$k; $i--){  
  5.             echo $char;  
  6.         }  
  7.         echo "<br>";  
  8.         $k=$k+1;  

Output:

Comments