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.
for
(PHP 4, PHP 5)
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 < sizeof($people); ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>
この書き方には問題があります。 このコードは実行速度が遅くなることでしょう。 配列のサイズを毎回計算しているからです。 サイズが変わることはないのですから、これは簡単に最適化することができます。 配列のサイズを変数に格納して、ループ内では sizeof ではなくその変数の値を使えばいいのです。 以下に例を示します。
<?php
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = sizeof($people); $i < $size; ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>
Here is another simple example for " for loops"
<?php
$text="Welcome to PHP";
$searchchar="e";
$count="0"; //zero
for($i="0"; $i<strlen($text); $i=$i+1){
if(substr($text,$i,1)==$searchchar){
$count=$count+1;
}
}
echo $count
?>
this will be count how many "e" characters in that text (Welcome to PHP)
Here is another simple example for " for loops"
<?php
$text="Welcome to PHP";
$searchchar="e";
$count="0"; //zero
for($i="0"; $i<strlen($text); $i=$i+1){
if(substr($text,$i,1)==$searchchar){
$count=$count+1;
}
}
echo $count
?>
this will be count how many "e" characters in that text (Welcome to PHP)
Alternating form rows:
<?php
$rows = 4;
echo '<table><tr>';
for($i = 0; $i < 10; $i++){
echo '<td>' . $i . '</td>';
if(($i + 1) % $rows == 0){
echo '</tr><tr>';
}
}
echo '</tr></table>';
?>
Changing $rows will change how many columns are in a row.
Just a note on looping through an array using the for() loop.
with the array...
<?php $array = array("value1","value2","value3"); ?>
then...
<?php
for(reset($array),current($array),next($array){
echo("Element ".key($array)." contains ".current($array)."<br/>";
}
?>
is the equivalent of...
<?php
for($i=0;$i<count($array);$i++){
echo("Element $i contains $array[$i]<br/>");
}
?>
I don't know if there is any advantage, just thought I would mention it.
Nested For Loop with the same iterator as the parent.
(Well formatted so the resulting code is clean when executed).
Useful for outputting a data array into a table, ie. images.
<?php
//Dummy data
$data = array(73,74,75,76,78,79,80,81,82,83,84,85,86,87);
//Our 'stepping' variable
$g = 0;
//Our rowcount
$rowcount = 0;
echo "<table cellspacing='0'>\r";
for ($i=0; $i<count($data); ) {
$rowcount++;
echo " <tr>\r"; //New row
$g = $i + 3; //Set our nested limit
for( ; $i<$g; $i++) { //nested for loop
if (!isset($data[$i])) { //Allow us to break on incomplete rows
break;
}
echo " <td style='border: 1px #000 solid;'>\r"; //Out put a cell
echo " <p>Row $rowcount <br/> Cell: $i <br/> Data: $data[$i]</p>\r";
echo " </td>\r";
}
echo " </tr> \r"; //End New Row
}
echo "</table>\r";?>
<?php
//this is a different way to use the 'for'
//Essa é uma maneira diferente de usar o 'for'
for($i = $x = $z = 1; $i <= 10;$i++,$x+=2,$z=&$p){
$p = $i + $x;
print "\$i = $i , \$x = $x , \$z = $z <br />";
}
?>
On the combination problem again...
It seems to me like it would make more sense to go through systematically. That would take nested for loops, where each number was put through all of it's potentials sequentially.
The following would give you all of the potential combinations of a four-digit decimal combination, printed in a comma delimited format:
<?php
for($a=0;$a<10;$a++){
for($b=0;$b<10;$b++){
for($c=0;$c<10;$c++){
for($d=0;$d<10;$d++){
echo $a.$b.$c.$d.", ";
}
}
}
}
?>
Of course, if you know that the numbers you had used were in a smaller subset, you could just plunk your possible numbers into arrays $a, $b, $c, and $d and then do nested foreach loops as above.
- Elizabeth
For those who are having issues with needing to evaluate multiple items in expression two, please note that it cannot be chained like expressions one and three can. Although many have stated this fact, most have not stated that there is still a way to do this:
<?php
for($i = 0, $x = $nums['x_val'], $n = 15; ($i < 23 && $number != 24); $i++, $x + 5;) {
// Do Something with All Those Fun Numbers
}
?>
Also acceptable:
<?php
for($letter = ord('a'); $letter <= ord('z'); $letter++)
print chr($letter);
?>
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n log n)), and you're still worried about loop speed, unroll your loops using e.g., Duff's Device:
<?php
$n = $ITERATIONS % 8;
while ($n--) $val++;
$n = (int)($ITERATIONS / 8);
while ($n--) {
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
}
?>
(This is a modified form of Duff's original device, because PHP doesn't understand the original's egregious syntax.)
That's algorithmically equivalent to the common form:
<?php
for ($i = 0; $i < $ITERATIONS; $i++) {
$val++;
}
?>
$val++ can be whatever operation you need to perform ITERATIONS number of times.
On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10 million) is:
Duff version: 7.9857 s
Obvious version: 27.608 s
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).
