downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

foreach> <do-while
[edit] Last updated: Fri, 24 May 2013

view this page in

for

(PHP 4, PHP 5)

Les boucles for sont les boucles les plus complexes en PHP. Elles fonctionnent comme les boucles for du langage C. La syntaxe des boucles for est la suivante :

for (expr1; expr2; expr3)
    commandes

La première expression (expr1) est évaluée (exécutée), quoi qu'il arrive au début de la boucle.

Au début de chaque itération, l'expression expr2 est évaluée. Si l'évaluation vaut TRUE, la boucle continue et l'instruction est exécutée. Si l'évaluation vaut FALSE, l'exécution de la boucle s'arrête.

À la fin de chaque itération, l'expression expr3 est évaluée (exécutée).

Les expressions peuvent éventuellement être laissées vides ou peuvent contenir plusieurs expressions séparées par des virgules. Dans expr2, toutes les expressions séparées par une virgule sont évaluées mais le résultat est obtenu depuis la dernière partie. Si l'expression expr2 est laissée vide, cela signifie que c'est une boucle infinie (PHP considère implicitement qu'elle vaut TRUE, comme en C). Cela n'est pas vraiment très utile, à moins que vous souhaitiez terminer votre boucle par l'instruction conditionnelle break.

Considérons les exemples suivants. Tous affichent les chiffres de 1 jusqu'à 10 :

<?php
/* exemple 1 */

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

/* exemple 2 */

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

/* exemple 3 */

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

/* exemple 4 */

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

Bien évidemment, le premier exemple est le plus simple de tous (ou peut être le quatrième), mais vous pouvez aussi penser qu'utiliser une expression vide dans une boucle for peut être utile parfois.

PHP supporte aussi la syntaxe alternative suivante pour les boucles for :

for (expr1; expr2; expr3):
    commandes
    ...
endfor;

Beaucoup de personnes ont l'habitude d'itérer grâce à des tableaux, comme dans l'exemple ci dessous.

<?php
/*
 * Ceci est un tableau avec des données que nous voulons modifier
 * au long de la boucle
 */
$people = array(
    array(
'name' => 'Kalle''salt' => 856412),
    array(
'name' => 'Pierre''salt' => 215863)
);

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

Ce code peut être lent parce qu'il doit calculer la taille du tableau à chaque itération. Etant donné que la taille ne change jamais, il peut facilement être optimisé en utilisant une variable intermédiaire pour stocker la taille au lieu d'appeler de façon répétitive la fonction 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(000000999999);
}
?>



foreach> <do-while
[edit] Last updated: Fri, 24 May 2013
 
add a note add a note User Contributed Notes for - [11 notes]
up
2
lishevita at yahoo dot co (notcom) .uk
6 years ago
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
up
2
JustinB at harvest dot org
7 years ago
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
}
?>
up
2
user at host dot com
9 years ago
Also acceptable:

<?php
 
for($letter = ord('a'); $letter <= ord('z'); $letter++)
   print
chr($letter);
?>
up
3
kanirockz at gmail dot com
3 years ago
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)
up
3
eduardofleury at uol dot com dot br
5 years ago
<?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 />";
   
}

?>
up
3
nzamani at cyberworldz dot de
11 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).
up
0
Philipp Trommler
6 months ago
Note, that, because the first line is executed everytime, it is not only slow to put a function there, it can also lead to problems like:

<?php

$array
= array(0 => "a", 1 => "b", 2 => "c", 3 => "d");

for(
$i = 0; $i < count($array); $i++){

echo
$array[$i];

unset(
$array[$i]);

}

?>

This will only output the half of the elements, because the array is becoming shorter everytime the for-expression counts it.
up
-1
bishop
9 years ago
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
up
-2
matthiaz
1 year 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
-2
dkimbel13 at gmail dot com
4 years ago
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.
up
-3
kanirockz at gmail dot com
3 years ago
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)

 
show source | credits | sitemap | contact | advertising | mirror sites