Search code examples
phpgotocontrol-structure

PHP goto control structure infinite execution


This seems to execute like an infinite loop.

a:
    echo "Statement 1 \n";
b:
    echo "Statement 2 \n";
if(1 > 2)
    goto a;
else
    goto b;

But this works correctly.

if(1 > 2)
    goto a;
else
    goto b;
a:
    echo "Statement 1 \n";
b:
    echo "Statement 2 \n";

What makes the difference.How can i execute some block of code again like in the first case.Example

$b = 1;
$c = 2;
$a = $b+$c;

if($a > $ b)
  // here i want to cal $a = $b+$c; without using function or copy pasting the code.

Solution

  • It is an infinite loop because... your code is an infinite loop!

        a:
            echo "...";
    .-- b: <------------.
    |       echo "..."; |
    |   if(1 > 2)       |
    |       goto a;     |
    |   else            |
    `-----> goto b; ----´
    

    It will output:

    Statement 1
    Statement 2
    Statement 2
    Statement 2
    Statement 2
    [...]
    

    Named sections of code (a: and b:) do not stop the script; they are just names that you can jump to. Named sections of code will always be executed if reached.