PHP goto Statement

PHPServer Side ProgrammingProgramming

Introduction

The goto statement is used to send flow of the program to a certain location in the code. The location is specified by a user defined label. Generally, goto statement comes in the script as a part of conditional expression such as if, else or case (in switch construct)

Syntax

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

After statement2, if expression (as a part of if statement) is true, program flow is directed to label1. If it is not true, statement3 will get executed. Program continues in normal flow afterwards.

In following example, If number input by user is even, program jumps to specified label

Example

 Live Demo

<?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";
?>

Output

This will produce following result −

x is an even number

The label in front of goto keyword can appear before or after current statement. If label in goto statement identifies an earlier statement, it constitutes a loop.

Foolowing example shows a loop constructed with goto statement

Example

 Live Demo

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

Output

This will produce following result −

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

Using goto, program control can jump to any named location. However, jumping in the middle of a loop is not allowed.

Example

 Live Demo

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

Output

This will produce following result −

PHP Fatal error: 'goto' into loop or switch statement is disallowed in line 5
raja
Published on 19-Sep-2020 13:14:00
Advertisements