Php para bucle con 2 variables?


Es posible hacer esto? (aquí está mi código)

for ($i = 0 ; $i <= 10 ; $i++){
  for ($j = 10 ; $j >= 0 ; $j--){
     echo "Var " . $i . " is " . $k . "<br>";
  }
}

Quiero algo como esto:

Var 0 es 10

Var 1 es 9

Var 2 es 8 ...

Pero mi código es incorrecto, da una lista enorme. Gurú Php, ayúdame !!

Author: jingleboy99, 2009-07-23

7 answers

Prueba esto:

for ($i=0, $k=10; $i<=10 ; $i++, $k--) {
    echo "Var " . $i . " is " . $k . "<br>";
}

Las dos variables $i y $k se inicializan con 0 y 10, respectivamente. Al final de cada bucle, $i se incrementará en uno ($i++) y $k se decrementará en uno ($k--). Así que $i tendrá los valores 0, 1, ..., 10 y $k los valores 10, 9, ..., 0.

 56
Author: Gumbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-23 15:24:45

No deberías usar dos for-loops para lo que te gustaría lograr ya que estás haciendo un bucle 121 veces en total (11x11). Lo que realmente quieres es tener un contador declarado fuera del bucle que rastrea j, y luego decrementar j dentro del bucle.

Editar: Gracias Gumbo por la captura de la inclusión para mí.

 1
Author: AlbertoPL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-23 15:33:37

Si, como su código parece, tiene dos valores que se ejecutan en la dirección opuesta, simplemente podría restar:

echo "Var " . $i . " is " . 10 - $i . "<br>";

Pero supongo que eso no es realmente lo que quieres? Además, tenga cuidado con el operador de coma sugerido. Si bien es algo bueno, puede causar efectos secundarios traviesos en otros lenguajes como C y C++ ya que PHP lo implementa de manera diferente.

 1
Author: bluebrother,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-23 15:41:52

También podría agregar una condición para la segunda variable

for ($i=0, $k=10; $i<=10, $k>=0 ; $i++, $k--) {
    echo "Var " . $i . " is " . $k . "<br>";
}
 1
Author: Mihail Minkov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-04 19:21:06

Para ampliar las otras respuestas (correctas), lo que estabas haciendo se llama anidando bucles. Esto significa que para cada iteración del bucle externo (el primero), estabas completando todo el bucle interno. Esto significa que en lugar de 11 salidas, obtienes 11 + 11 + 11 + ... = 11 * 11 salidas

 0
Author: Sean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-23 15:28:05
array_map(function($i) {
    echo "Var {$i} is ".(10-$i)."<br/>".PHP_EOL; 
}, range(1,10));
 0
Author: jlettvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-30 07:08:40

Traté de obtener una hora de inicio y finalización y almacenarla en la base de datos, dada una hora de inicio y finalización, usted loop a través de cada vez utilizando dos variables i y j

   $start = "09:00";
   $end = "18:00";
   $strEnTim = strtotime("10.00");

   $slotStart = strtotime($start);
   $slotEnd = strtotime($end);
   $slotNow = $slotStart;

   for( $i=$slotStart, $j=$strEnTim; $i, $j<=$slotEnd; $i+=3600,  $j+=3600) 
   {
        if(( $i < $slotNow) && ( $j < $strEnTim)) continue;
        Slot::create([
            'start_time' => date("H:i",$i),
            'end_time' => date("H:i", $j)
        ]);
   }
 0
Author: Chika Ugwuanyi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-25 15:03:46