
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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
- Related Articles
- goto statement in C/C++
- C program to explain the goto statement
- How can I use goto statement in JavaScript?
- Why doesn't JavaScript have a goto statement?
- Is there a goto statement available in bash on Linux?
- PHP break Statement
- PHP declare Statement
- PHP include Statement
- PHP include_once Statement
- PHP require Statement
- PHP require_once Statement
- PHP return Statement
- PHP continue Statement
- PHP switch Statement
- Goto in Arduino
