PHP में  goto keyword का use हम  Program  में किसी दूसरे section पर move करने के लिए करते हैं।  Targeted Section को हम label के through define करते हैं और उसी Specified label को goto keyword के साथ target करते हैं।

PHP goto Syntax

  goto targeted_level;
  level_name:
  {
    //do something here;
  }

PHP goto Example

File : goto.php

Copy Fullscreen Close Fullscreen
<?php               
  goto my_level;
  my_level:
  {
    echo "This is simple goto test";
  }
?>
Output
This is simple goto test

Note - Targeted label same file और same context में होना चाहिए , ऐसा नहीं हो सकता कि आप किसी function के अंदर define किये गए label को function के बाहर Access करें। और न ही For Loop या  While Loop को jump कर सकते हैं

See Example :


File : goto2.php

Copy Fullscreen Close Fullscreen
<?php               
 goto end;
 for($i=0; $i<10; $i++) 
 {
  end:
    echo 'Not working';
 }
?>
Output
PHP Fatal error: 'goto' into loop or switch statement is disallowed in C:\xampp\htdocs\test\goto2.php on line 6

तो आप Example में देख सकते हैं कि जब हम For Loop के अंदर define किये गए label को access करते हैं तो PHP Fatal Error Generate करती है।

हालांकि हम For Loop या  While Loop के अंदर से बाहर define किये गए labels को आसानी से Access कर सकते हैं।

For Example :

File : goto3.php

Copy Fullscreen Close Fullscreen
<?php               
 for($i=0; $i<10; $i++) 
 {
   if($i==3)
     goto end;
 }

 end:
 echo 'Awesome it works';
?>
Output
Awesome it works

One more thing , जब हम For Loop या  While Loop  के अंदर से बाहर define किये गए labels को Access करते हैं तो जैसे ही goto statement execute होता है तो loop भी break हो जाता है , means हम पूरी तरह से Loop को exit कर देतें हैं।

For Example ऊपर दिए गए example में ही अगर हम $i की value print करें तो ये values तभी तक print होंगी जब तक कि goto statement Executeनहीं हो जाता।

File : goto4.php

Copy Fullscreen Close Fullscreen
<?php               
 for($i=0; $i<10; $i++) 
 {
   if($i==3)
     goto end;
   
  /*printing values*/
  echo $i."<br>";
 }

 end:
 echo 'Awesome it works';
?>
Output
0
1
2
Awesome it works

I Hope अब आपको PHP में goto के बारे में अच्छे से समझ में आ गया होगा।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers