Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semicolon after closing curly bracket in PHP

Tags:

php

I am writing a script to make chunks of a text and send it via SMS. Earlier today i was reviewing some code to split the string in chunks and i saw something I've never seen before. I'm talking about the ";" right after the "}" at the en of the snippet.

Why this colon? i know it works but i don't know if it adds some semantics or some instruction to the interpreter, anybody know what is this for?

while(1)
{
    $length = (strlen($output)+strlen($words[$i]));
    if($length>$new_max)
    {
        if(count($words) > 0)
        {
            $out_array[] = $output;
            $output = '';

        }
        else
        {
            break;    
        }
    }
    else
    {
        $output = $output." ".$words[$i];
        ++$i;
    };
};

EDIT: Looks clear that the semicolons as well as multiple semicolons together has no effect over the result, but, do you know if it has some effect to the interpreter? is it doing some task (internally) when it parses it?

like image 590
SubniC Avatar asked Nov 30 '10 15:11

SubniC


2 Answers

I think that those 2 semicolons do nothing here. It is probably being interpreted as an empty expression immediately following the if/while.

like image 135
Evan Teran Avatar answered Sep 20 '22 22:09

Evan Teran


In some cases you need to have a semicolon after a closing curly bracket!

Example:

if(1==1):
    if(true){ echo "it's true"; } //no semicolon here => syntax error!
else:
    echo "no never ever";
endif;

Of course you would't use alternative syntax for control structures if there is only php code.

But if you have a mix of HTML and PHP code you could use the alternative syntax for control structures (alternate syntax makes the code only clearer and easyer to read), but the problem then is that in some cases a plugin or for example a tag parser of a cms could produce an if statement with curly brackets (without a "closing semicolon") just before the "else:" and this would lead to a syntax error in the resulting php file.

The above code would work like this:

if(1==1):
    if(true){ echo "it's true"; }; 
else:
    echo "no never ever";
endif;
like image 33
user3228587 Avatar answered Sep 22 '22 22:09

user3228587