PHP goto Statement 🎯

beginner
12 min

PHP goto Statement 🎯

Welcome to your PHP journey! Today, we'll dive into one of the control structures in PHP - the goto statement. This powerful tool can help you jump to a specific location in your code, but be careful, it's often discouraged due to its potential to create spaghetti code.

Before we start, let's understand the purpose of the goto statement:

  • The goto statement allows you to jump directly to a labeled statement within the same function.

Basic Use of goto πŸ“

To use the goto statement, we first need to create a label (an identifier followed by a colon :) before the line we want to jump to. Then, we can use the goto keyword followed by the label name to jump there.

php
<?php start: echo "You are at the start\n"; goto end; echo "You will not see this"; end: echo "You are at the end\n"; ?>

In the above example, we have a labeled statement start, and we've used the goto statement to jump directly to the end label, skipping the line You will not see this.

Jumping out of Loops πŸ’‘

One common use of the goto statement is to break out of loops. In the following example, we'll use the goto statement to exit a loop when a specific condition is met.

php
<?php $i = 0; outer: for ($j = 0; $j < 10; $j++) { if ($i === 5) { goto outer; } echo $j . "\n"; $i++; } echo "Loop exited\n"; ?>

In this example, we've created a loop (outer labeled statement) that will run 10 times. If $i equals 5, we use the goto statement to jump to the outer label, effectively breaking out of the loop.

Quiz

Quick Quiz
Question 1 of 1

What does the `goto` statement do in PHP?

Remember, while the goto statement can be useful in certain situations, it's important to avoid creating overly complex code that's hard to understand and maintain.

Happy coding! πŸ₯³