lundi 18 janvier 2016
Boucle do-while
(PHP 4, PHP 5, PHP 7)
boucles do-while sont très semblables aux boucles while, mais l'expression est testée à la fin de chaque itération plutôt le début. La principale différence à la boucle while est que la première itération d'une boucle do-while est garanti pour fonctionner (l'expression de la vérité est vérifiée uniquement à la fin de l'itération), alors qu'il peut ne pas fonctionner nécessairement avec une boucle régulière tout (la l'expression de la vérité est vérifié au début de chaque itération, si elle est évaluée à FALSE dès le début, l'exécution de la boucle ne se terminerait immédiatement).
Il ya juste une syntaxe pour les boucles do-while:
0 );
?>
La boucle ci-dessus irait à un moment exactement, puisque après la première itération, lorsque l'expression de la vérité est cochée, il évalue à FALSE ($ i est pas plus grand que 0) et l'exécution de la boucle se termine.
Les utilisateurs avancés de C peuvent être familier à une utilisation différente de la boucle do-while, qui permet de stopper l'exécution dans le milieu de blocs de code, en les encapsulant dans un do-while (0), et en utilisant la pause déclaration. Le fragment de code suivant illustre ceci:
Ne vous inquiétez pas si vous ne comprenez pas ce droit de suite ou pas du tout. Vous pouvez écrire des scripts très très puissants sans utiliser cette fonctionnalité. Depuis PHP 5.3.0, il est possible d'utiliser goto opérateur à la place de ce hack.
ajouter une note ajouter une note
Contributions utilisateurs 9 notes
en haut
en bas
7 jayreardon arobase gmail point com ¶ il y a 8 ans
There is one major difference you should be aware of when using the do--while loop vs. using a simple while loop: And that is when the check condition is made.
In a do--while loop, the test condition evaluation is at the end of the loop. This means that the code inside of the loop will iterate once through before the condition is ever evaluated. This is ideal for tasks that need to execute once before a test is made to continue, such as test that is dependant upon the results of the loop.
Conversely, a plain while loop evaluates the test condition at the begining of the loop before any execution in the loop block is ever made. If for some reason your test condition evaluates to false at the very start of the loop, none of the code inside your loop will be executed.
en haut
en bas
3 Martin ¶ il y a 8 mois
Do-while loops can also be used inside other loops, for example:
' ;
print_r ( $numbers );
echo '' ;
?>
en haut
en bas
2 Shaida dot mca arobase gmail point com ¶ il y a 5 ans
Example of Do while :-
en haut
en bas
-11 Ryan ¶ Il y a 7 ans
I've found that the most useful thing to use do-while loops for is multiple checks of file existence. The guaranteed iteration means that it will check through at least once, which I had trouble with using a simple "while" loop because it never incremented at the end.
My code was:
0) ..." says that
if the loop has already been run at least once, then there
is now a number at the end of the filename and we can
simply increment that. Otherwise, we have to place a
number at the end of the filename, which is where $i
comes in even handier */
if( $i > 0 ) $filename [ 0 ]++;
else $filename [ 0 ] = $filename [ 0 ]. $i ;
$i ++;
} while( file_exists ( "uploaded/" . $filename [ 0 ]. "." . $filename [ 1 ]));
/* Now that everything is uploaded, we should move it
somewhere it can be accessed. Hence, the "uploaded"
folder. */
move_uploaded_file ( $_FILES [ 'file' ][ 'tmp_name' ], "uploaded/" . $filename [ 0 ]. "." . $filename [ 1 ]);
?>
I'm sure there are plenty of ways of doing this without using the do-while loop, but I managed to toss this one together in no-time flat, and I'm not a great PHP programmer. =) It's simple and effective, and I personally think it works better than any "for" or "while" loop that I've seen that does the same thing.
en haut
en bas
-13 andrew au NOSPAM Dot Dot com devohive ¶ Il y a 7 ans
I'm guilty of writing constructs without curly braces sometimes... writing the do--while seemed a bit odd without the curly braces ({ and }), but just so everyone is aware of how this is written with a do--while...
a normal while:
a do--while:
Also, a practical example of when to use a do--while when a simple while just won't do (lol)... copying multiple 2nd level nodes from one document to another using the DOM XML extension
document_element ();
$newDoc = domxml_new_doc ( '1.0' ); // new document we want to copy to
$newRoot = $newDoc -> create_element ( 'rootnode' );
$newRoot = $newDoc -> append_child ( $newRoot ); // this is the node we want to copy to
# loop through nodes and clone (using deep)
$child = $fileRoot -> first_child (); // first_child must be called once and can only be called once
do $newRoot -> append_child ( $child -> clone_node ( true )); // do first, so that the result from first_child is appended
while ( $child = $child -> next_sibling () ); // we have to use next_sibling for everything after first_child
?>
en haut
en bas
-12 david dot schueler à Tel-billig point de ¶ il y a 4 ans
If you are trying to use a construct like this:
It will NOT loop as expected, because the continue tries to run the "next" loop, but the expression says just "false" so there is no next loop. The continue exits the while loop.
To get around this you may use an other expression, like this
or use the goto statement since PHP 5.3.
en haut
en bas
-12 Jantsch arobase gmail point com ¶ il y a 8 ans
Useful when you want to continue to read a recordset that was already being read like in:
1 ){
do{
// processing the records till the end
}while( $rs = mysql_fetch_row( $res ));
}
?>
en haut
en bas
-17 xiaomao5 au point com en direct ¶ il y a 4 ans
Another hack
If you want $type to only have a value of 0 or 1, you can do this:
en haut
en bas
-29 Renseignements au point dans pkrules ¶ il y a 2 ans
Notice the way of using the loops:-
$arr =array( "orange" , "banana" , "apple" , "raspberry" );
$i = 0 ;
while( $i < count ( $arr )){
$a = $arr [ $i ];
echo $a . "
" ;
$i ++;
}
/*
orange
banana
apple
raspberry
*/
echo "
" ;
$i = 0 ;
$c = count ( $arr );
while( $i < $c ){
$a = $arr [ $i ];
echo $a . "
" ;
$i ++;
}
/*
orange
banana
apple
raspberry
*/
echo "
" ;
while( $a = $arr [ 1 *-- $i ]){
echo $a . "
" ;
if( $i <= 0 )break;
}
echo "
" ;
/*
orange
banana
apple
raspberry
*/
foreach( $arr as $i ){
print $i ;
echo "
" ;
}
/*
orange
banana
apple
raspberry
*/
?
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire