Please need help

how to print this series using for loop only
2 4 6 8 10 12
12 13 14 15 16 17
17 18 19 20 21
21 22 23 24 25 26

What have you tried?

I have tried using nested for loop

for($i=1;$i<=4;$i++){
   for($j=1;$j<=7;$j++){
     echo $j*2;
}
echo "<br>";
}

Play with the rules until you get it to print what you want…

for($i=1;$i<=4;$i++){
	for($j=1;$j<=($i % 3 == 0 ? 5 : 6);$j++){
		if($last <12){
			$last = $j*2;
		} elseif($j == 1) {
			//$last = $last -1;
		} elseif($last >= 12) {
			$last += 1;
		}
		echo "$last\t";
	}
	echo "\n";
}
1 Like
<?php

for(true;;){
echo '2 4 6 8 10 12
12 13 14 15 16 17
17 18 19 20 21
21 22 23 24 25 26';
break;
}
1 Like

Learning loops does have practical purposes as I just updated my vanilla javascript game (I’m still doing it) and I had to configure my database table to be compatible with my JSON. I didn’t feeling reconfiguring my MySQL Database Table, so I rewrote some PHP using loops and other functions.

    /*
     * Put database table in proper array format in order that
     * JSON will work properly.
     */
    foreach ($data as $qdata) {
        foreach ($qdata as $key => $value) {
            switch ($key) {
                case 'answer1':
                    $answers['answers'][$index] = $value;
                    break;
                case 'answer2':
                    $answers['answers'][$index + 1] = $value;
                    break;
                case 'answer3':
                    $answers['answers'][$index + 2] = $value;
                    break;
                case 'answer4':
                    $answers['answers'][$index + 3] = $value;
                    break;
            }
        } // foreach inner

        unset($qdata['answer1']);
        unset($qdata['answer2']);
        unset($qdata['answer3']);
        unset($qdata['answer4']);
        
        $finished = array_merge($qdata, $answers);
        $mData[$indexArray] = $finished;
        $indexArray++;
    }

I just wanted to share this as it does come in handy.

Why does the third line only have 5 numbers? If there is some spesific rule for that it will dictate how you have to code it

Sponsor our Newsletter | Privacy Policy | Terms of Service