How to Create Triangle in PHP

How to create a triangle in php, This is a very common question for beginner and intermediate-level programmers. I will share a script that will generate a triangle using PHP.

This is a very common type of question in interviews. The programming languages can vary but the question will same as how to generate a triangle.

We’ll cover the following topics here:

  • Create a right angle using a number.
  • Create a right angle using *.
  • Create a triangle using *.

Sample code in php to generate Right Angle:

The Below php code will use to create a right angle from 1- 9.

<?php
for ($i=0; $i<=9; $i++) {  
 for($j=1; $j<=$i; $j++) {  
	echo $i ."  ";  
  } 
  echo "\n";
}

Output:

right-angle

PHP Star Triangle Program Example

The below code are creating right angle using star(*).

<?php
for($i=0;$i<10;$i++){  
	for($j=1;$j<$i;$j++){  
		echo "* ";  
	}  
echo "\n";  
}

Output:

right-angle-php

PHP Number Triangle Program in PHP

The Below PHP code will use to create a Triangle from 1- 10.

for ($i=9; $i&gt;=1; $i--) {  
  for($j=1; $j&lt;=$i; $j++) {  
     echo ' ';  
  }
  $j--;
for ($k=1; $k&lt;=(10-$j); $k++) {  
    echo " # ";   
}  
echo "\n";
}

Output:


right-angle2

You can download source code and Demo from below link.

3 thoughts on “How to Create Triangle in PHP

Leave a Reply

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