PHP 8.3.4 Released!

for

(PHP 4, PHP 5, PHP 7, PHP 8)

for ループは、PHPで最も複雑なループです。 for は、Cのforループと同様に動作します。 forループの構文は、次のようになります。

for (式1; 式2; 式3)
    文

最初の式(式1)は、ループ開始時に無条件に 評価(実行)されます。

各繰り返しの開始時に、式2が評価されます。 その式の値がtrueが場合、ループは継続され、括弧 内の文が実行されます。値がfalseの場合、ループの 実行は終了します。

各繰り返しの後、式3が評価(実行)されます。

各式は空にすることもできますし、複数の式をカンマで区切って指定することもできます。 式2 でカンマ区切りの式を使用すると、 すべての式を評価します。しかし、結果として取得するのは最後の式の結果となります。 式2 を空にすると、無限実行ループになります (PHP は、この状態を C 言語のように暗黙の内に true とみなします)。 この機能は、初心者が想像するよりもずっと便利です。 for の式の結果ではなく条件付き break 文を使ってループを終了させたくなることもしばしばあります。

次の例について考えてみましょう。以下の例はすべて 1 から 10 までの数を表示します。

<?php
/* 例 1 */

for ($i = 1; $i <= 10; $i++) {
echo
$i;
}

/* 例 2 */

for ($i = 1; ; $i++) {
if (
$i > 10) {
break;
}
echo
$i;
}

/* 例 3 */

$i = 1;
for (; ; ) {
if (
$i > 10) {
break;
}
echo
$i;
$i++;
}

/* 例 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>

もちろん、最初の例(もしくは 4番目の例)が最善であると考えられます。 しかし、forループにおいて空の式を使用できると、 多くの場合、便利だということに気づかれるかと思います。

PHPは、forループ用に"コロン構文"もサポートします。 for loops.

for (式1; 式2; 式3):
    文;
    ...
endfor;

多くのユーザーにとって、次の例のように配列をループ処理することはよくあるでしょう。

<?php
/*
* データが入った配列で、ループ処理中に
* その中身を書き換えたいと考えています
*/
$people = array(
array(
'name' => 'Kalle', 'salt' => 856412),
array(
'name' => 'Pierre', 'salt' => 215863)
);

for(
$i = 0; $i < count($people); ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
?>

このコードは実行速度が遅くなることでしょう。 というのも、配列のサイズを毎回取得しているからです。 サイズが変わることはありえないのだから、これは簡単に最適化することができます。 配列のサイズを変数に格納して使うようにすれば、 何度も count() を呼ばずに済むのです。

<?php
$people
= array(
array(
'name' => 'Kalle', 'salt' => 856412),
array(
'name' => 'Pierre', 'salt' => 215863)
);

for(
$i = 0, $size = count($people); $i < $size; ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
?>

add a note

User Contributed Notes 2 notes

up
309
matthiaz
12 years ago
Looping through letters is possible. I'm amazed at how few people know that.

for($col = 'R'; $col != 'AD'; $col++) {
echo $col.' ';
}

returns: R S T U V W X Y Z AA AB AC

Take note that you can't use $col < 'AD'. It only works with !=
Very convenient when working with excel columns.
up
70
nzamani at cyberworldz dot de
22 years ago
The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops.
So you should try to take everything that doesn't change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:

<?php
for ($i = 0; $i <= somewhat_calcMax(); $i++) {
somewhat_doSomethingWith($i);
}
?>

Faster would be:

<?php
$maxI
= somewhat_calcMax();
for (
$i = 0; $i <= $maxI; $i++) {
somewhat_doSomethingWith($i);
}
?>

And here a little trick:

<?php
$maxI
= somewhat_calcMax();
for (
$i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ;
?>

The $i gets changed after the copy for the function (post-increment).
To Top