PHP goto 语句

phpserver side programmingprogramming更新于 2025/7/18 17:22:17

简介

goto 语句用于将程序流程发送到代码中的特定位置。该位置由用户定义的标签指定。通常,goto 语句作为条件表达式的一部分出现在脚本中,例如 if、else 或 case(在 switch 结构中)

语法

statement1;
statement2;
if (expression)
   goto label1;
statement3;
label1: statement4;

在语句2之后,如果表达式(作为if语句的一部分)为真,程序流程将定向到标签1。如果不为真,则将执行语句3。之后程序继续按正常流程运行。

在以下示例中,如果用户输入的数字为偶数,程序将跳转到指定的标签

示例

<?php
$x=(int)readline("enter a number");
if ($x%2==0)
   goto abc;
echo "x is an odd number";
return;
abc:
echo "x is an even number";
?>

输出

这将产生以下结果 −

x is an even number

goto 关键字前的标签可以出现在当前语句之前或之后。如果 goto 语句中的标签标识了更早的语句,则构成循环。

以下示例展示了一个用 goto 语句构造的循环

示例

<?php
$x=0;
start:
$x++;
echo "x=$x
"; if ($x<5)    goto start; ?>

输出

这将产生以下结果 −

x=1
x=2
x=3
x=4
x=5

使用 goto 指令,程序控制可以跳转到任意指定位置。但是,不允许在循环中间跳转。

示例

<?php
for ($x=1; $x<=5; $x++){
   if (x==3)
      goto inloop;
   for ($y=1;$y<=5; $y++){
      inloop:
      echo "x=$x y=$y
";    } } ?>

输出

这将产生以下结果 −

PHP Fatal error: 'goto' into loop or switch statement is disallowed in line 5

相关文章