Home > Backend Development > PHP Tutorial > Detailed explanation of the use of php goto statement

Detailed explanation of the use of php goto statement

黄舟
Release: 2023-03-11 12:34:01
Original
2294 people have browsed it

This article mainly introduces what is the PHP goto statement and the usage examples of gotooperator. Friends who need it can refer to it

goto operator can be used to jump to the program a specified location in . The target location can be marked with the target name followed by a colon. Goto in PHP has certain restrictions and can only jump within the same file and scope. This means that you cannot jump out of a function or class method, nor can you jump into another function. You also cannot jump into any loop or switch structures. Common usage is to break out of a loop or switch, which can replace multi-layer break.

The usage is very simple: put the mark of the target position after goto, and mark the target position with the target name plus a colon, as follows:

Copy code Code As follows:

<?php
goto a;echo &#39;Foo&#39;;
//此句被略过
a:echo &#39;Bar&#39;;
//上面的例子输出结果为: 
Bar;
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;;
//上面的例子输出结果为: j hit 17
?>
Copy after login

Note:
The goto operator is only valid in PHP 5.3 and above.

The following writing methods are invalid

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

The above routine will output:

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

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template