
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP Goto Statement
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
<?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
<?php $x=0; start: $x++; echo "x=$x
"; 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
<?php for ($x=1; $x<=5; $x++){ if (x==3) goto inloop; for ($y=1;$y<=5; $y++){ inloop: echo "x=$x y=$y
"; } } ?>
Output
This will produce following result −
PHP Fatal error: 'goto' into loop or switch statement is disallowed in line 5