MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

while

Los bucles while son los tipos de bucle más simples en PHP. Se comportan como su contrapartida en C. La forma básica de una sentencia while es:

while (expr) sentencia

El significado de una sentencia while es simple. Le dice a PHP que ejecute la(s) sentencia(s) anidada(s) repetidamente, mientras la expresión while se evalúe como TRUE. El valor de la expresión es comprobado cada vez al principio del bucle, así que incluso si este valor cambia durante la ejecución de la(s) sentencia(s) anidada(s), la ejecución no parará hasta el fin de la iteración (cada vez que PHP ejecuta las sentencias en el bucle es una iteración). A veces, si la expresión while se evalúa como FALSE desde el principio de todo, la(s) sentencia(s) anidada(s) no se ejecutarán ni siquiera una vez.

Como con la sentencia if, se pueden agrupar multiples sentencias dentro del mismo bucle while encerrando un grupo de sentencias con llaves, o usando la sintaxis alternativa:

while (expr): sentencia ... endwhile;

Los siguientes ejemplos son idénticos, y ambos imprimen números del 1 al 10:

<?php
/* ejemplo 1 */
 
 $i = 1;
 while ($i <= 10) {
     print $i++;  /* el valor impreso ser&iacute;a
                     $i antes del incremento
                     (post-incremento) */
 }
 
 /* ejemplo 2 */
 
 $i = 1;
 while ($i <= 10):
     print $i;
     $i++;
 endwhile;
?>



add a note add a note User Contributed Notes
while
startide at free dot fr
27-Apr-2006 08:08
Talking about while, dropdown menus, and ternary operator which was mentionned before, you can combine them to have drop menu built with a value selected according to your wishses.

<select name="whatever">
<?php
while ($data = mysql_fetch_assoc($requeteID))
{
 
$menu .= '<option value="'.$data['id'].'"';
 
$menu .= ($data['id'] == $_GET['id'] ? ' selected>' :'>');
 
$menu .= $data['name'].'</option>';
}
?>
</select>

Therefore if you are creating a form to select data from database, and want the form displayed when search is done to show what parameters have been chosen that will do the trick !!

Let's say I make a search between different sports, I choose football in my form, send my query... then displays are show, the menu will have football selected because of the ternary operator that displays "selected>" on the <option> ;) Enjoy ^^
sub7ime at yahoo dot com
04-Apr-2006 12:00
I was reading the excellent post by wbryson at gmail dot com and I wanted to just add that the ? : syntax is known as the 'ternary operator' for those who want to learn more about it.
chris mushy
11-May-2005 06:43
Just a note to stuart - the reason for this behaviour is because using the while(value = each(array)) construct increments the internal counter of the array as its looped through. Therefore if you intend to repeat the loop, you need to reset the counter. eg:

$one = array("10", "20", "30", "40");
$two = array("a", "b", "c", "d");

$i=0;
while($i < count($one)) {
   reset($two);
   while($a = each($two)) {
       echo $a[1]." - ".$one[$i].", ";
   }
   $i++;
  
}

This produces:

a - 10, b - 10, c - 10, d - 10, a - 20, b - 20, c - 20, d - 20, a - 30, b - 30, c - 30, d - 30, a - 40, b - 40, c - 40, d - 40,
stuart
11-May-2005 02:06
A note to anyone nesting a while loop inside a while loop....

Consider the example below:

$one = array("10", "20", "30", "40");
$two = array("a", "b", "c", "d");

$i=0;
while($i < count($one)) {
  
   while($a = each($two)) {
       echo $a[1]." - ".$one[$i].", ";
   }
   $i++;
  
}

This will return the following:
a - 10, b - 10, c - 10, d - 10

So in effect the main while loop is only doing one iteration... and not 4 as expected....

Now the example below works as expected..
$i=0;
while($i < count($one)) {
  
   foreach($two as $a) {
       echo $a." - ".$one[$i]."\n";
   }
   $i++;
  
}

by returning:
a - 10, b - 10, c - 10, d - 10, a - 20, b - 20, c - 20, d - 20, a - 30, b - 30, c - 30, d - 30, a - 40, b - 40, c - 40, d - 40

So there is clearly a difference on how while statements work in comparison to other looping structures.

I think it would be good to have an explaination of this strange behaviour.
13-Mar-2005 09:54
virtualjosh at yahoo dot com (Hosh) wrote on: 16-Aug-2003 12:52

The speedtest is interesting. But the seemingly fastest way contains a pitfall for beginners who just use it because it is fast and fast is cool ;)

Walking through an array with next() will cut of the first entry, as this is the way next() works ;)

If you really need to do it this way, make sure your array contains an empty entry at the beginning. Another way would be to use

<?php
while ($this = current($array) ){
  
do_something($this);
  
next($array);
}
?>

There is an impact on speed for sure but I did not test it. I would advise to stick with conventional methods because current(),next() in while loops is too error prone for me.
Ilene Jones
21-Feb-2005 01:12
For Perl programmers, break is similar to last

while (1) {
   while(cond) {
       if (error) {
           break 2; // in perl this could have been last;
       }
   }
}
corychristison[AT]NSPAMlavacube[dot]com
03-Dec-2004 03:08
While can do wonders if you need something to queue writing to a file while something else has access to it.

Here is my simple example:

<?php

 
function write ($data, $file, $write_mode="w") {
  
$lock = $file . ".lock";
    
// run the write fix, to stop any clashes that may occur
  
write_fix($lock);
    
// create a new lock file after write_fix() for this writing session
  
touch( $lock );
    
// write to your file
  
$open = fopen($file, $write_mode);
  
fwrite($open, $data);
  
fclose($open);
    
// kill your current lock
  
unlink($lock);
  }

  function
write_fix ($lock_file) {
   while(
file_exists($lock_file){
    
// do something in here?
     // maybe sleep for a few microseconds
     // to maintain stability, if this is going to
     // take a while ?? [just a suggestion]
  
}
  }

?>

This method is not recommended for use with programs that will be needing a good few seconds to write to a file, as the while function will eat up alot of process cycles.  However, this method does work, and is easy to implement.  It also groups the writing functions into one easy to use function, making life easier. :-)
virtualjosh at yahoo dot com (Hosh)
15-Aug-2003 03:52
I made a test traversing an array (simple, but long, numeric array with numeric keys). My test had a cycle per method, and multiplied each array element by 100.. These were my results:

******************************************************
30870 Element Array Traversing

[test_time] [BEGINS/RESETS @ time_start = 1060977996.689]
0.2373 seg later -> while (list ($key, $val) = each ($array)) ENDS

[test_time] [BEGINS/RESETS @ time_start = 1060977996.9414]
0.1916 seg later -> while (list ($key,) = each ($array))  ENDS

[test_time] [BEGINS/RESETS @ time_start = 1060977997.1513]
0.1714 seg later -> foreach ($array AS $key=>$value) ENDS

[test_time] [BEGINS/RESETS @ time_start = 1060977997.3378]
0.0255 seg later -> while ($next = next($array)) ENDS

[test_time] [BEGINS/RESETS @ time_start = 1060977997.3771]
0.1735 seg later -> foreach ($array AS $value) ENDS
**************************************************************

foreach is fatser than a while (list  - each), true.
However, a while(next) was faster than foreach.

These were the winning codes:

$array = $save;
test_time("",1);
foreach ($array AS $key=>$value)
   $array[$key] = $array[$key] * 100;
test_time("foreach (\$array AS \$key=>\$value)");

$array = $save;
test_time("",1);
reset($array);
while ($next = next($array))
{    $key = key($array);
   $array[$key] = $array[$key] * 100;
}       
test_time("while (\$next = next(\$array))");
*********************************************************
The improvement seems huge, but it isnt that dramatic in real practice. Results varied... I have a very long bidimensional array, and saw no more than a 2 sec diference, but on 140+ second scripts.  Notice though that you lose control of the $key  value (unless you have numeric keys, which I tend to avoid), but it is not always necessary. 

I generally stick to foreach. However, this time, I was getting Allowed Memory Size Exceeded errors with Apache. Remember foreach copies the original array, so this now makes two huge 2D arrays in memory and alot of work for Apache. If you are getting this error, check your loops. Dont use the whole array on a foreach. Instead get the keys and acces the cells directlly. Also, try and use unset and Referencing on the huge arrays.

Working on your array and loops is a much better workaround than saving to temporary tables and unsetting (much slower).
Merve
10-Jul-2003 09:49
This is an easy way for all you calculator creators to make it do factorials. The code is this:

<?php
$c
= ($a-1);
$d = $a;
while (
$c>=1)
{
$a = ($a*$c);
$c--;
}
print (
" $d! = $a");
?>

$a changes, and so does c, so we have to make a new variable, $d, for the end statement.
Merve
10-Jul-2003 08:39
Here's something really cool and simple. Using the while loop, you can calculate exponents (powers). The code looks like this:

<?php
//Since the values of $a and $b will be changing,
//we need to assign new variables to them, $c and $d.
$c = $a;
$d = $b;
while (
$b>1)
{
//Here we're changing the value of $a.
$a = ($a*$c);
//Here we're changing the value of $b
$b--;
}
//And to top it all off, a little statement at the end.
print (" $c<sup>$d</sup> &#61; $a");
?>

This code works because we are subtracting 1 from the value of $b each time through the loop. Since we're saying that $a = ($a*$c), we are changing the value of $a but not the value of $c. We need the variables $c and $d for the statement at the end because the values of $a and $b have changed. This is a really simple trick that most of you could have figured out in a matter of seconds, but it is a good trick for beginners like me.
redshift at pandora dot be
03-Jul-2003 06:48
You can use break in your while loop to stop execution of the loop, and continue to resume it.
bens at effortlessis dot com
25-Jun-2003 05:32
I recently did a performance analysis, comparing while() and foreach() when traversing an array.

Foreach() is nearly 2x faster - an effect most notable when traversing large, multi-dimensional arrays.

Here's my code:
<?

for ($i=0; $i<10000; $i++)
      
$a[$i]=$i*2;

echo
"list time: \n".$start=mktime()."\n";
for (
$i=0; $i<1000; $i++)
       {
      
reset($a);
       while(list(
$k, $v)=each($a))
               {
               echo
"";
               }
       }
echo (
$finish=mktime())."\n";
$result=$finish-$start;
echo
"Result: $result seconds\n\n";

echo
"for time: \n".$start=mktime()."\n";
for (
$i=0; $i<1000; $i++)
       {
       foreach(
$a as $k => $v)
               {
               echo
"";
               }
       }
echo (
$finish=mktime())."\n";
$result=$finish-$start;
echo
"Result: $result seconds\n\n";
?>

And here's the results on an 1800+ Athlon:
list time:
1056579474
1056579512
Result: 38 seconds

fore time:
1056579512
1056579533
Result: 21 seconds
destes at ix dot netcom dot com dot nospam
19-Jun-2003 10:17
Be very careful about the exact syntax of your condition clause.  Specifically, if you're not careful, you can easily get an infinite loop, and will wonder why the PHP page isn't loading.  For example:

<?php
while ($loop = TRUE) {
   ...
}
?>

Instead of $loop == TRUE.  This is a common mistake but it hurts more when it's in a structure like a while().
bob at kiwi-interactive dot com
16-May-2003 12:08
I noticed the post above about building a multi coloumn table and making use of the : operator

I did mine this way
----------------------
<table>
  <?php // get the list of categories
            
$list_of_cats=new links();
          
$list_of_cats->show_list_of_cats();
          
          
$total_cats=count($list_of_cats->list_of_cats);
          
$a=0;
          
$b=0;
           while(
$a<$total_cats) {
               if(
$b==0) {
                   echo(
"\n<tr>");
               }
               echo(
"\n<td><input type=\"checkbox\" name=\"id_".$a."\" value=\"".$list_of_cats->list_of_cats[$a]["id"]."\">
&nbsp;"
.$list_of_cats->list_of_cats[$a]["category"]."</td>");
               if(
$b==1) {
                   echo(
"</tr>\n");
                  
$b=0;
                  
$last_tr=true;
               } else {
                  
$b++;
                  
$last_tr=false;
               }
              
$a++;
           }
          
// did the last one add a tr if not add a blank one?
          
if(!$last_tr) {
              
// nope
              
echo("<td>&nbsp;</td></tr>");
           }
        
?>
</table>
---------------------------------
This will build a 2 coloumn table and populate each (it was part of a form). If the bottom right cell is lefte empty (that is you have an odd number of items) it correctly adds a blank cell and closes the table (XHTML valid)
skinnerd at nettally dot com
11-Apr-2003 09:54
Using the ":" and endwhile; in lieu of the curly braces allowed me to nest an if else condition within the while statement as in the following:
//Sets $count at 1 initially
$count=1; 
//Loads thumbnail images in table 3 columns wide, select images to load
$result = mysql_query("SELECT URLImage, FileName, URLThumb, FileNameThumb, DatePhotographed, Comment  FROM PLANTS, WEBIMAGES WHERE WEBIMAGES.PID='$PID' and WEBIMAGES.PID=PLANTS.PID");

<?php
while ( $row = mysql_fetch_array($result) ) :
 
//Check to see if this is 3rd image and if so, close the table row and reset the count to 1

if ($count==3){
   echo(
'<TD><A HREF="' . $row['URLImage'] . '' . $row['FileName'] . '">');
   echo(
'<IMG SRC=' . $row['URLThumb'] . '' . $row['FileNameThumb'] .'  ALT="Click to see full sized image"></A><br>');
   echo(
'<center><FONT SIZE=-1>DATE: ' . $row['DatePhotographed'] . '<br>' . $row['Comment'] . '</center></font><br></TD></TR><TR>');
  
$count=1;
 
//If this is not the 3rd image, add the image in the table and add 1 to the count
 
}else{
   echo(
'<TD><A HREF="' . $row['URLImage'] . '' . $row['FileName'] . '">');
   echo(
'<IMG SRC=' . $row['URLThumb'] . '' . $row['FileNameThumb'] .'  ALT="Click to see full sized image"></A><br>');
   echo(
'<center><FONT SIZE=-1>DATE: ' . $row['DatePhotographed'] . '<br>' . $row['Comment'] . '</center></font><br></TD>');
  
$count++;
  }
endwhile;
?>

It would not work nested within the curly braces of the while conditional.
tcn at pandora dot be
05-Apr-2003 04:46
When you do a while loop like this:

<?php
$String
=array ("a","b","c");
$i=0;
while (
$String[$i])
     {
     echo
$String[$i];
    
$i++;
       }
?>

And error reporting is set to E_ALL you get a warning message saying there's an undefined index.

There's a simple solution to this:

<?php
$String
=array ("a","b","c);
$i=0;
while ($i<count($String))
   {
   echo $String[$i];
   $i++;
     }
?>

And away the warning is!
12-Dec-2002 01:48
do {

   statement...;

} while (condition);

it is another good choice.
chayes at antenna dot nl
26-Feb-2002 02:42
At the end of the while (list / each) loop the array pointer will be at the end.
This means the second while loop on that array will be skipped!

You can put the array pointer back with the reset($myArray) function.

example:

<?php
$myArray
=array('aa','bb','cc','dd');
 while (list (
$key, $val) = each ($myArray) ) echo $val;
reset($myArray);
 while (list (
$key, $val) = each ($myArray) ) echo $val;
?>
moriarty at all-ears dot co dot uk
13-Feb-2002 12:58
If you want to skip an iteration of a while loop, you can use continue.

This will result in the rest of the present iteration being skipped, and it will go back to the start of the loop for the next iteration.

Moriarty
yohgaki at hotmail dot com
01-Apr-2001 01:09
If you want to traverse array, foreach() is faster than while() a little.
[Benched with PHP4.0.4pl1/Apache DSO/Linux]

i.e.
foreach ($array as $k => $v)
is a little faster than
while (list($k,$v) = each($array))

You might want to use foreach for large arrays.

Citas célebres

La televisión es goma de mascar para los ojos.

Frank L. Wright
Arquitecto estadounidense
(1867-1959)
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_034.jpg
Contenidos Web

Chiste de... Tiendas
Chorizo a medida

En la charcutería:

- Córteme ese chorizo en rajas pequeñas.

El charcutero empieza a cortar y a cortar y cuando lleva un rato pregunta:

- ¿Ya?
- No, no, siga que ya le diré yo.

El charcutero sigue y cuando le queda ya casi solo un culito del chorizo dice el tío:

-Pare, pare, esa es la raja que quiero
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_065.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0075.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid