Usage example of goto in php (code)

不言
Release: 2023-04-04 12:30:01
forward
2711 people have browsed it

The content of this article is about the usage examples (code) of goto in php. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Let’s give a simple example first:

<?php
goto LABEL; //这个标签自定义echo &#39;乔峰&#39;;

LABEL:echo &#39;鸠摩智&#39;;
Copy after login

The above routine will output: Jiumozhi

Explanation: 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.

Let’s look at another example:

<?php
for($i=0, $j=10; $i<20; $i++) {
    while($j--) {
        if($j==6)
            goto end;
    }
}
echo"这里不会被输出";
end:
echo "i = $i\n";
echo &#39;stop here&#39;;
Copy after login

You can see above that the output after end is directly output, continue reading:

$number = 1;
switch($number){
    case 1:
        goto one;                 //使用goto跳到one标记处
        echo "第一名";            //goto已经跳转,这条语句不执行
    case 2:
        goto two;
        echo "第二名";
    case 3:
        goto three;
        echo "第三名";
}

one:
echo " 武林第一!";
//exit;
two:
echo " 武林第二!";
//exit;
three:
echo " 武林第三!";
//exit;
/*
  最终结果是:武林第一! 武林第二! 武林第三!
  注意后面的exit 注释了,为何不是最终输出 武林第一,大家可以琢磨下。
*/
Copy after login

Although goto is not used much. But sometimes it is very efficient in certain scenarios.

The above is the detailed content of Usage example of goto in php (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.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