Home >Backend Development >PHP Problem >What is the usage of php goto statement?

What is the usage of php goto statement?

藏色散人
藏色散人Original
2021-06-11 10:30:332672browse

php The goto statement is used like "goto a;echo 'Foo';a:echo 'Bar';", where the goto operator can be used to jump to another location in the program; the target location can It is marked with the target name plus a colon, and the jump instruction is marked with the target location after goto.

What is the usage of php goto statement?

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

php goto statement usage

goto

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

What is the usage of php goto statement?

What's the worse thing that could happen if you use goto?

This comic credits » xkcd

The goto operator can be used to jump to another location in the program. The target position can be marked with the target name followed by a colon, and the jump instruction is the goto followed by the mark of the target position. Goto in PHP has certain restrictions. The target location can only be in the same file and scope, which means that it cannot jump out of a function or class method, nor can it jump into another function. It also cannot jump into any loop or switch structure. You can jump out of a loop or switch. The usual usage is to use goto instead of multiple levels of break.

Example#1 goto example

<?php
goto a;
echo &#39;Foo&#39;;
 
a:
echo &#39;Bar&#39;;
?>

The above routine will output:

Bar

Example#2 goto jump out of the loop example

<?php
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    if($j==17) goto end; 
  }  
}
echo "i = $i";
end:
echo &#39;j hit 17&#39;;
?>

The above routine will output :

j hit 17

Example #3 The following writing is invalid

<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    loop:
  }
}
echo "$i = $i";
?>

The above routine will output:

Fatal error: &#39;goto&#39; into loop or switch statement is disallowed in
script on line 2

Note:

goto operator is only available in PHP 5.3 and The above version is valid.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the usage of php goto statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn