Home > Article > Backend Development > php—goto statement
The
goto operator can be used to jump to another location in the program. The target position can be marked with the target name plus a colon, and the jump instruction is the mark of the target position after goto. goto in PHP has certain restrictions. The target location can only be in the same file and scope, which means that it cannot jump out of a function or class method, nor can it jump into another function. It also cannot jump into any loop or switch structure. You can jump out of a loop or switch. The usual usage is to use goto instead of multi-layer break.
Example #1 goto example
<?php goto a; echo 'Foo'; a: echo 'Bar'; ?>
The above routine will output:
Bar
Example #2 goto jump out of loop example
<?php for($i=0,$j=50; $i<100; $i++) { while($j--) { if($j==17) goto end; } } echo "i = $i"; end: echo 'j hit 17'; ?>
The above routine will output:
j hit 17
Example #3 below Invalid writing method
<?php goto loop; for($i=0,$j=50; $i<100; $i++) { while($j--) { loop: } } echo "$i = $i"; ?>
The above routine will output:
Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2
Note: The
goto operator is only valid in PHP 5.3 and above. .