Activity 5. PHP Loops


Problem 1

Write a PHP script that will output the following using loop.

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

Solution

$num = 5;
$char = "*";
for ($i=1; $i <= $num; $i++) { 
    echo $char;
    $char .= " *";
    echo "\n";
}

Output

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

Problem 2

Write a PHP script that will output the following using loop.

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

Solution

$num = 5;
$char = "*";
for ($i=1; $i <= $num*2; $i++) {
    if ($i <= $num) {
        echo str_repeat(" *", $i);
        echo "\n";
    } else{
        echo str_repeat(" *", $num*2 + 1 - $i);
        echo "\n";
    } 
}

Output

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

Problem 3

Create a script using a for loop to add all the integers between 0 and 10 and display the total. The range should be user inputted.

Solution

HTML Forms for user input
<form class="form-horizontal" method="get" action="addIntegersHandle.php">
    <legend>Add Integers to n (user input)</legend>
    <label class="control-label" for="num">Number 1</label>
    <input type="number" class="form-control" id="inputDefault" name="num">
    <button type="submit" class="btn btn-primary" id="calcSubmit">Submit</button>
</form>

PHP Code
if(isset($_GET['num'])){
    $num = $_GET['num'];
    $tot = 0;
    for ($i=1; $i <=$num ; $i++) { 
        $tot += $i;
    }
    echo "Sum between 1 to " . $num . " " . "is: " . $tot;
}

Output

Demo

Problem 4

Write a PHP script that creates the following table (use for loops).

Solution

for ($i=1; $i <= $num3; $i++) {
    echo "<tr>";

    for ($j=1; $j <= $num3; $j++) { 
        echo "<td>" . $j * $i . "</td>";
    }
    echo "</tr>";
}

Output

12345678910
2468101214161820
36912151821242730
481216202428323640
5101520253035404550
6121824303642485460
7142128354249566370
8162432404856647280
9182736455463728190
102030405060708090100