Zaboy
Zaboy

Reputation: 47

loop with symbol minus and number php

i have this code .

echo "<br>";

$start = 1;
$angka = $_POST[angka];
$a = $angka;

for($i=$start; $i<=$angka; $i++) {
    for($j=$start;$j<=$angka;$j=$j+2){
        echo $i;
        if($j < $angka) echo $a;
    }
    $a--;
    echo '<br>';
}

Reference: Print Looping for dynamic row php

This is not my expecting result . First i want the result like this .

-2-4-
1-3-5
-2-4-
1-3-5
-2-4-

The rule is Number of rows and columns follow the number of numbers declared.If the declaration of the number 5, then the results will be displayed are 5 rows and 5 columns like the example above.

Upvotes: 2

Views: 76

Answers (1)

Josua M C
Josua M C

Reputation: 3158

i think this code is working

<?php
$_POST['angka'] = 5;
$angka = $_POST['angka'];

for($i=1; $i<=$angka; $i++) {
    for($j=1;$j<=$angka;$j++){
        if($i%2 == 1) {
            if($j%2 == 0) {
                echo $j;
            } else {
                echo '-';
            }
        } else  {
            if($j%2 == 0) {
                echo '-';
            } else {
                echo $j;
            }
        }
    }
    echo '<br>';
}

Result:

-2-4-
1-3-5
-2-4-
1-3-5
-2-4-

Upvotes: 1

Related Questions