In this post we will learn to print name triangle pattern in PHP. We will print the name triangle pattern in two ways. The first name triangle will be in increasing order and the second in decreasing order.


How To Print Name Triangle Pattern In PHP - 4 ?


Name Triangle Pattern In PHP

Name Triangle Pattern is printed in two ways step by step like this:

First Name Triangle

To print this type of pattern in PHP, we follow the following steps:

Step 1: First let's take a string "CodexRadar" and store it in the $str variable. Then count the length of the string using the strlen() function and store it in the $count variable. Then print this string with a for loop.

<?php
$str = "CodexRadar";
$count = strlen($str);
for($i = 0; $i < $count; $i++) {
echo $str[$i ];
echo "<br/>";
}
?> code-box

Output :
C
o
d
e
x
R
a
d
a
r

Step 2: In this step take a second for loop and print the first name triangle.

<?php
$str = "CodexRadar";
$count = strlen($str);
for($i = 0; $i < $count; $i++) {
for($j = 0; $j <= $i; $j++) {
echo " ".$str[$j]." ";
}
echo "<br/>";
}?> code-box

Output :
C
C o
C o d
C o d e
C o d e x
C o d e x R
C o d e x R a
C o d e x R a d
C o d e x R a d a
C o d e x R a d a r

Second Name Triangle

To print this name triangle in step 2 we replace $i++ with $i-- and $j <= $i with $j < $i. The complete code as follows:

<?php
$str = "CodexRadar";
$count = strlen($str);
for($i = 0; $i < $count; $i--) {
for($j = 0; $j < $i; $j++) {
echo " ".$str[$j]." ";
}
echo "<br/>";
}?> code-box

Output :
C o d e x R a d a r
C o d e x R a d a
C o d e x R a d
C o d e x R a
C o d e x R
C o d e x
C o d e
C o d
C o
C

Summary

In this post we learn how to print name triangle pattern in PHP. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post