Home >Backend Development >PHP Tutorial >Examples of use of goto statement in PHP

Examples of use of goto statement in PHP

little bottle
little bottleforward
2019-04-23 15:45:262458browse

This article mainly talks about how to use goto in PHP. It has certain reference value. Interested friends can learn about it.

Let’s give a simple example first:

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

The above routine will output: Jiumozhi

Explanation:
goto operator can be used to jump to the program another location in. 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:

<?phpfor($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;;

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 注释了,为何不是最终输出 武林第一,大家可以琢磨下。*/

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

Related tutorials: PHP video tutorial

The above is the detailed content of Examples of use of goto statement in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete