w3resource

PHP for loop Exercises: Using nested for loop, construct a specific pattern

PHP for loop: Exercise-4 with Solution

Create a script to construct the following pattern, using a nested for loop.

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

Pictorial Presentation:

PHP for loop Exercises: Using nested for loop, construct a specific pattern

Sample Solution:

PHP Code:

<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo '\n';
}
for($i=$n; $i>=1; $i--)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo '\n ';
}
?>

Sample Output:

 *                                                          
 *  *                                                       
 *  *  *                                                    
 *  *  *  *                                                 
 *  *  *  *  *                                              
 *  *  *  *  *                                              
 *  *  *  *                                                 
 *  *  *                                                    
 *  *                                                       
 * 

Flowchart :

Flowchart: Using nested for loop, construct a specific pattern

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Create a script to construct the specific pattern, using nested for loop.
Next: Write a program to calculate and print the factorial of a number using a for loop. The factorial of a number is the product of all integers up to and including that number, so the factorial of 4 is 4*3*2*1= 24.

What is the difficulty level of this exercise?



PHP: Tips of the Day

Get the full URL in PHP

Have a look at $_SERVER['REQUEST_URI'], i.e.

Example:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

(Note that the double quoted string syntax is perfectly correct)

If you want to support both HTTP and HTTPS, you can use

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Editor's note: using this code has security implications. The client can set HTTP_HOST and REQUEST_URI to any arbitrary value it wants.

Ref : https://bit.ly/2ZYItNJ