PHP goto Statement Usage Example

  • 2021-12-19 06:03:09
  • OfStack

Problem

When PHP is executing the code process, at a certain time, we want it to jump to a specific location to continue executing the code. What should we do?

Answer

In PHP, we can use the goto operator to make the PHP code executor jump to a specific location in the program. The use of goto has a certain limit, such as: you can't jump out of a function or class, you can't jump into a function from outside, and you can't jump into any loop or switch structure. But you can jump out of the loop or switch, and the common usage is to use goto instead of break nested with multiple layers in switch.

Grammar

goto causes PHP to jump directly to the specified flag position.


goto  Sign ;

 Code block 

 Sign :

 Code block 

Example

Example 1--Try to jump into a loop


<?php

goto loop;

for($i=0; $i<3; $i++) {

  while($i++) {

    loop:

  }

}

echo "End";

Run results:


Fatal error: 'goto' into loop or switch statement is disallowed in F:\index.php on line 3

It can be seen from the running results that goto cannot jump directly into the loop from the outside.

Example 2--A Simple Jump


<?php

goto loop;

echo ' This is the first 1 Sentences. ';

loop:

echo ' This is the first 2 Sentences. ';
·

The above is all about PHP goto statement usage. Thank you for your support for this site.


Related articles: