php講座

繰り返し処理

ループ

while
while(条件式){
  繰り返したい処理
}

条件式が真である間、処理が繰り返される

do..while
do{
  繰り返したい処理
}while(条件式);

まず一回は処理がなされ、その後条件式が真である間、処理が繰り返される

for
for(処理1;条件式;処理2){
  繰り返したい処理
}

ループ回数をループ文の中で独立して制御するときに用いる(詳細は例題より)

ループ処理の中断(ループから抜ける)
break
loop1.php
<?php
$num = $_GET['num'];
?>
<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="UTF-8" />
   <title>ループ</title>
</head>
<body>
<h1>連呼プログラム</h1>
<form action="" method="get">
何回連呼しますか?
<input type="number" name="num" max="10" min="0">
<div><input type="submit" value="決定"></div>
</form>
<?php

//while1ループ
$count = 0;  //count変数の初期化
while($count < $num){
?>
<p><?php print $count+1;?>.超(while)</p>
<?php
    $count++; //count変数インクリメント
}

//while2ループ
$count = 0;  //count変数の初期化
while(true){ //無限ループ
    if($count >= $num){ //$countが$num以上になったら
        break;          //ループから抜ける
     }
?>
<p style="font-size:1.2em"><?php print $count+1;?>.超(while,break)</p>
<?php
    $count++; //count変数インクリメント
}

//do-whileループ
$count = 0;;  //count変数の初期化
do{
?>
<p style="font-size:1.5em"><?php print $count+1;?>.超(do-while)</p>
<?php
    $count++; //count変数インクリメント
}while($count < $num);

//forループ
for($i = 0; $i < $num; $i++){ //count変数(ここでは$i)の初期化からインクリメントまで1行で書ける
?>
<p style="font-size:1.8em"><?php print $i+1;?>.いい感じ!(for)</p>
<?php
}
?>
</body>
</html>

多重ループ

loop2.php
<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="UTF-8" />
   <title>多重ループ</title>
</head>
<body>
<h1>多重ループ</h1>
<?php
for($i = 0; $i < 10; $i++){
    for($j = 0; $j < $i; $j++){
        print "[{$i}{$j}]";
    }
    print '<br>';
}
?>
<hr>
<?php
for($i = 9; $i >= 0; $i--){
    for($j = 0; $j < $i; $j++){
        print "[{$i}{$j}]";
    }
    print '<br>';
}
?>
<hr>
<?php
for($i = 9; $i >= 0; $i--){
    for($j = 9; $j > $i; $j--){
        print "[{$i}{$j}]";
    }
    print '<br>';
}
?>
</body>
</html>

カウント用変数は一番外側からi > j > k と下げていくのが一般的