บทนำ
คำสั่ง goto ใช้ส่งโฟลว์ของโปรแกรมไปยังตำแหน่งเฉพาะในโค้ด ตำแหน่งระบุโดย label ที่ผู้ใช้กำหนด โดยทั่วไป goto statement จะอยู่ในสคริปต์เป็นส่วนของนิพจน์เงื่อนไข เช่น if, else หรือ case (ใน switch construct)
รูปแบบไวยากรณ์
statement1; statement2; if (expression) goto label1; statement3; label1: statement4;
หลัง statement2 หากนิพจน์ (เป็นส่วนของคำสั่ง if) เป็นจริง โฟลว์โปรแกรมจะถูกนำไปยัง label1 หากไม่จริง statement3 จะถูกดำเนินการ โปรแกรมดำเนินต่อไปตามปกติหลังจากนั้น
ในตัวอย่างต่อไปนี้ หากตัวเลขที่ผู้ใช้ป้อนเป็นเลขคู่ โปรแกรมจะกระโดดไป label ที่ระบุ:
ตัวอย่าง
<?php $x=(int)readline("enter a number"); if ($x%2==0) goto abc; echo "x is an odd number"; return; abc: echo "x is an even number"; ?>
ผลลัพธ์
x is an even number
Label หน้าคีย์เวิร์ด goto อาจปรากฏก่อนหรือหลังคำสั่งปัจจุบัน หาก label ใน goto statement ระบุคำสั่งก่อนหน้า จะเป็นลูป (loop)
ตัวอย่างต่อไปนี้แสดงลูปที่สร้างด้วย goto statement:
ตัวอย่าง
<?php $x=0; start: $x++; echo "x=$x\n"; if ($x<5) goto start; ?>
ผลลัพธ์
x=1 x=2 x=3 x=4 x=5
ใช้ goto ควบคุมโปรแกรมกระโดดไปตำแหน่งที่ตั้งชื่อได้ อย่างไรก็ตาม ไม่สามารถกระโดดเข้าไปกลางลูปได้
ตัวอย่าง
<?php for ($x=1; $x<=5; $x++){ if (x==3) goto inloop; for ($y=1;$y<=5; $y++){ inloop: echo "x=$x y=$y\n"; } } ?>
ผลลัพธ์
PHP Fatal error: 'goto' into loop or switch statement is disallowed in line 5