Home >Backend Development >PHP Tutorial >PHP syntax: goto statement
Question
When PHP is executing code, at a certain moment we want it to jump to a specific location to continue executing the code. What should we do?
Answer
In PHP, we can use the goto operator to make the PHP code executor jump to a specific location in the program. The use of goto has certain limitations, such as: it cannot jump out of a function or class, it cannot jump into a function from the outside, and it cannot jump into any loop or switch structure. But you can jump out of a loop or switch. The usual usage is to use goto instead of multiple nested breaks in switch.
Syntax
goto will cause PHP to jump directly to the specified flag position.
goto 标志; 代码块 标志: 代码块
Example
Example 1 - Trying to jump into a loop
<?php goto loop; for($i=0; $i<3; $i++) { while($i++) { loop: } } echo "End";
Running result:
Fatal error: 'goto' into loop or switch statement is disallowed in F:\index.php on line 3
From running As a result, it can be seen that goto cannot jump directly into the loop from the outside.
Example 2 - A simple jump
<?php goto loop; echo '这是第一个句子。'; loop: echo '这是第二个句子。';
Run result:
这是第二个句子。
Example 3 - Break out of the loop
<?php for($i=0; $i<10; $i++) { while($i++) { if($i==5) goto end; } } echo '此时 $i=10'; end: echo '此时 $i=' . $i;
Run result:
此时 $i=5
As can be seen from the running results of Example 3, it is very convenient to use goto when we need to jump out of the loop.
Tips
Although goto is very convenient to use, arbitrary use of goto statements can easily cause code logic confusion, so it should be used with caution.
The above is the detailed content of PHP syntax: goto statement. For more information, please follow other related articles on the PHP Chinese website!