Triangle of asterisks in php
395
I am having problems creating a triangle in php. This is my code.
for($i = 0; $i <= $input; $i++) {
for($j = 1; $j <= $i; $j++) {
echo " $char  ";
}
echo "<br>";
}
The result is this.
*
* *
* * *
* * * *
* * * * *
But what I'm trying to do is this.
*
* *
* * *
* * * *
* * * * *
What should I change with my codes?
Answer
Solution:
There is a native PHP function str_pad where you can say how to pad the string in one of directions:
STR_PAD_RIGHT
,STR_PAD_BOTH
,STR_PAD_LEFT
See it live: https://eval.in/927835
Here was used
STR_PAD_BOTH
:And here
STR_PAD_LEFT
:Answer
Solution:
You have to make sure space is printed the correct number of times.
So first we will loop through all the white spaces, from 1 to $input - $i. here we will print the white space. Then we will loop through the astricks the number of $i times.
Note: we are using   two times for alignment purpose with astrick
Here is the code:
Answer
Solution:
Create your main character string and "padding" string separately, then echo the concatenated result: