Using GOTO Operator

In this tutorial, you’ll create a goto operator loop. The goto operator performs a jump to a specified label (line) within the same file.

This tutorial covers the following topics:

  1. Create a goto loop
  2. Use goto operator inside a function
  3. Use goto operator inside a loop

PHP 5.3.0 introduced the goto statement, which performs a jump to a specified label (line) within the same file. A label is a name followed by a colon :.

 $i = 5;
 if ($i < 10)
  goto jump;

 //This will be jumped
 echo '';

 echo 'This should be printed.';

Create a goto loop


$i = 0;
if ($i < 10) {
 echo "$i ";
 goto REPEAT;

echo '<br>Finished goto loop';

The above example shows the following result on the web browser window:

Make a loop using goto operator

Use goto inside function

The target label must be within the same script file and scope. You cannot jump out of a function or method, nor can you jump into one.

function abc(){
 //some code
 goto jump;

echo '....';

The above example prints the following fatal error:

PHP Fatal error: 'goto' to undefined label "jump"...

Use goto inside a loop

 $resultsToFetch = 100;
 $resultsFetched = 0;


 $results = rand(5,20);
 while (true){
  $resultsFetched += $results;
  if ($resultsFetched < $resultsToFetch)
   goto FetchMore;

echo $resultsFetched;

PHP Control Structures:

  1. If elseif else and Switch Case Conditional Statements
  2. Conditional Expressions
  3. Ternary, Elvis, and Null Coalescing Operators
  4. Using Loops
  5. Using GOTO Operator