You should mention the label can't be a variable
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Imagen proporcionada por » xkcd
El operador goto
puede ser utilizado para continuar
la ejecución del script en otro punto del programa.
El destino es especificado por una etiqueta sensible a mayúsculas y minúsculas,
seguida de dos puntos, y la instrucción goto
es luego
seguida de esta etiqueta. goto
no está totalmente sin limitaciones.
La etiqueta de destino debe estar en el mismo contexto y fichero, lo que significa
que no es posible cambiar de método o función,
ni ir a otra función. Asimismo, es imposible entrar
en una estructura de bucle o un switch
.
Sin embargo, es posible salir de ellas, y el uso común es entonces utilizar
goto
como un break
.
Ejemplo #1 Ejemplo con goto
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?>
El ejemplo anterior mostrará :
Bar
Ejemplo #2 Ejemplo de bucle con goto
<?php
for ($i = 0, $j = 50; $i < 100; $i++) {
while ($j--) {
if ($j == 17) {
goto end;
}
}
}
echo "i = $i";
end:
echo 'j hit 17';
?>
El ejemplo anterior mostrará :
j hit 17
Ejemplo #3 Este goto
no funciona
<?php
goto loop;
for ($i = 0, $j = 50; $i < 100; $i++) {
while ($j--) {
loop:
}
}
echo "$i = $i";
?>
El ejemplo anterior mostrará :
Fatal error: 'goto' into loop or switch statement is disallowed in script on line 2
the problem of goto is that it is a good feature but in a large codebase it reduces the readability of the code . that's all . i try to not use it to think about the person who is going to read after me .
You can use goto to hide large HTML blocks without using echo():<html><body><?php if ($hide_form_and_script) { goto label_1;} ?><form action="" method="post"><!-- some HTML here --></form><script>let a='test'; // no need to escape nested quotes as with echo()// some JavaScript here</script><?php label_1: ?></body></html>
You can jump inside the same switch. This can be usefull to jump to default<?php$x=3;switch($x){ case 0: case 3: print($x); if($x) goto def; case 5: $x=6; default: def: print($x);}?>
In example #2 use do-while instead:<?phpdo { for ($i = 0, $j = 50; $i < 100; $i++) { while ($j--) { if ($j == 17) { break 3; } } } echo "i = $i";} while(false);echo 'j hit 17';?>