Goto Statement(Label/Operator) in PHP : Tutorial


(Since PHP 5.3)


The goto statement is used to jump to another section in the program.

The PHP goto has some restrictions.

1. The Target label must be within the same file and context.
2. Goto cannot jump out of a function or method or into another function.
3. Goto cannot jump into any sort of loop or switch structure.

Example 1:
<?php 

echo "1<br>";
echo "2<br>";

goto five; //Target label is five

echo "3<br>";
echo "4<br>";

five: //Label Target

echo "5<br>";
echo "6<br>";
echo "7<br>";
echo "8<br>";
echo "9<br>";
echo "10<br>";


?>
Output

1 2 5 6 7 8 9 10


Example 2: Jumping out of the loop is possible
<?php 

$i=1;

//goto cannot jump into loops!!


while($i<5)
{
	echo "Hello..<br>";
	$i++;
	goto OutOfLoop; //Control goes out of the loop to the Label
	
}
OutOfLoop:
echo "End..";

?>
Output

Hello.. End..


Example 3: Goto cannot jump into a loop!
<?php 

$i=1;

//goto cannot jump into loops!!
goto OutOfLoop;

while($i<5)
{
	echo "Hello..";
	$i++;
	OutOfLoop:
}

echo "End..";

?>
Output

Fatal error: 'goto' into loop or switch statement is disallowed in I:\xampp\htdocs\xampp\Tutorials\GotoTest.php on line 4

As seen in the above example that when goto is used to jump into a loop an Fatal error is thrown and the script is terminated!.
Goto is available only since PHP 5.3.