PHP syntax: goto statement

藏色散人
Release: 2023-04-07 07:12:01
forward
10726 people have browsed it

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 标志;
代码块
标志:
代码块
Copy after login

Example

Example 1 - Trying to jump into a loop

<?php
goto loop;
for($i=0; $i<3; $i++) {
    while($i++) {
        loop:
    }
}
echo "End";
Copy after login

Running result:

Fatal error: &#39;goto&#39; into loop or switch statement is disallowed in F:\index.php on line 3
Copy after login

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 &#39;这是第一个句子。&#39;;
loop:
echo &#39;这是第二个句子。&#39;;
Copy after login

Run result:

这是第二个句子。
Copy after login

Example 3 - Break out of the loop

<?php
for($i=0; $i<10; $i++) {
    while($i++) {
        if($i==5) goto end;
    }
}
echo &#39;此时 $i=10&#39;;
end:
echo &#39;此时 $i=&#39; . $i;
Copy after login

Run result:

此时 $i=5
Copy after login

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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template