PHP

The goto operator

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 :.

<?php
$user = $_GET['user'] ?? 'Guest';
$userMenu = "$user profile."; 
if ($user == 'Guest')
 goto jump;

//This will be jumped if $user is equal to Guest.
echo $userMenu;

//label
jump:
echo 'This should be printed.';

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.

<?php
function abc(){
 //some code
 goto jump;
}
abc();

//...
jump:
echo '....';

Above example prints the following fatal error:

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

Use goto inside a loop

$resultsToFetch = 100;
$resultsFetched = 0;

FetchMore:

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

echo $resultsFetched;
Advertisement:
Advertisement: