curly brackets necessary in php?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • deko

    #1

    curly brackets necessary in php?


    Do I need to use curly brackets in PHP if .. else statements? other constructs?
    Does it matter? What are Best Practices? Why?

    thanks in advance...

    This seems to work WITHOUT curly brackets:

    if(ereg("Win", getenv("HTTP_US ER_AGENT")))
    $visos = "Windows";
    elseif((ereg("M ac", getenv("HTTP_US ER_AGENT"))) || (ereg("PPC",
    getenv("HTTP_US ER_AGENT"))))
    $visos = "Mac";
    elseif(ereg("Li nux", getenv("HTTP_US ER_AGENT")))
    $visos = "Linux";
    elseif(ereg("Fr eeBSD", getenv("HTTP_US ER_AGENT")))
    $visos = "FreeBSD";
    elseif(ereg("Su nOS", getenv("HTTP_US ER_AGENT")))
    $visos = "SunOS";
    elseif(ereg("IR IX", getenv("HTTP_US ER_AGENT")))
    $visos = "IRIX";
    elseif(ereg("Be OS", getenv("HTTP_US ER_AGENT")))
    $visos = "BeOS";
    elseif(ereg("OS/2", getenv("HTTP_US ER_AGENT")))
    $visos = "OS/2";
    elseif(ereg("AI X", getenv("HTTP_US ER_AGENT")))
    $visos = "AIX";
    else $visos = "unknown";

    And this seems to work WITH curly brackets:

    if (isset($_SERVER ))
    {
    if (isset($_SERVER["HTTP_X_FORWARD ED_FOR"]))
    {
    $visip = $_SERVER["HTTP_X_FORWARD ED_FOR"];
    }
    elseif (isset($_SERVER["HTTP_CLIENT_IP "]))
    {
    $visip = $_SERVER["HTTP_CLIENT_IP "];
    }
    else
    {
    $visip = $_SERVER["REMOTE_ADD R"];
    }
    }
    else
    {
    if (getenv('HTTP_X _FORWARDED_FOR' ))
    {
    $visip = getenv('HTTP_X_ FORWARDED_FOR') ;
    }
    elseif (getenv('HTTP_C LIENT_IP'))
    {
    $visip = getenv('HTTP_CL IENT_IP');
    }
    else
    {
    $visip = getenv('REMOTE_ ADDR');
    }
    }


  • Andy Hassall

    #2
    Re: curly brackets necessary in php?

    On Sun, 21 Mar 2004 00:35:18 GMT, "deko" <dje422@hotmail .com> wrote:
    [color=blue]
    >Do I need to use curly brackets in PHP if .. else statements? other constructs?
    >Does it matter? What are Best Practices? Why?[/color]

    You need to use curly brackets if there is more than one statement to be
    executed in that conditional branch.

    if (condition)
    statement;
    else
    statement2;

    if (condition) {
    statement;
    } else {
    statemen2;
    }

    if (condition) {
    statement1;
    statement2;
    } else
    statement2;

    All these are fine.

    A conditional itself is a single statement, so even:

    if (condition1)
    if (condition2)
    statement1;
    else
    statement2;

    If you only have one statement, you can leave out the curly brackets, which
    cuts out a couple of lines and may make the code more (or less) readable.

    The risk is that later you add another statement, and forget to add the curly
    brackets:

    if (condition)
    statement1;
    statement2;

    statement2 will in fact always be executed, even if condition is false.

    Same principle applies to all the control structures; while, foreach, etc.

    --
    Andy Hassall <andy@andyh.co. uk> / Space: disk usage analysis tool
    http://www.andyh.co.uk / http://www.andyhsoftware.co.uk/space

    Comment

    • deko

      #3
      Re: curly brackets necessary in php?

      I'll have to admit, those curly brackets are a pain. But it would seem better
      to ALWAYS use curly brackets for consistency's sake. Do many programmers do
      this? Or is it pretty much a free for all?

      "Andy Hassall" <andy@andyh.co. uk> wrote in message
      news:dirp50d3l9 k3fipna6bdvs1di 6eo0uh5pa@4ax.c om...[color=blue]
      > On Sun, 21 Mar 2004 00:35:18 GMT, "deko" <dje422@hotmail .com> wrote:
      >[color=green]
      > >Do I need to use curly brackets in PHP if .. else statements? other[/color][/color]
      constructs?[color=blue][color=green]
      > >Does it matter? What are Best Practices? Why?[/color]
      >
      > You need to use curly brackets if there is more than one statement to be
      > executed in that conditional branch.
      >
      > if (condition)
      > statement;
      > else
      > statement2;
      >
      > if (condition) {
      > statement;
      > } else {
      > statemen2;
      > }
      >
      > if (condition) {
      > statement1;
      > statement2;
      > } else
      > statement2;
      >
      > All these are fine.
      >
      > A conditional itself is a single statement, so even:
      >
      > if (condition1)
      > if (condition2)
      > statement1;
      > else
      > statement2;
      >
      > If you only have one statement, you can leave out the curly brackets, which
      > cuts out a couple of lines and may make the code more (or less) readable.
      >
      > The risk is that later you add another statement, and forget to add the curly
      > brackets:
      >
      > if (condition)
      > statement1;
      > statement2;
      >
      > statement2 will in fact always be executed, even if condition is false.
      >
      > Same principle applies to all the control structures; while, foreach, etc.
      >
      > --
      > Andy Hassall <andy@andyh.co. uk> / Space: disk usage analysis tool
      > http://www.andyh.co.uk / http://www.andyhsoftware.co.uk/space[/color]


      Comment

      • Pedro Graca

        #4
        Re: curly brackets necessary in php?

        deko wrote:[color=blue]
        > I'll have to admit, those curly brackets are a pain. But it would seem better
        > to ALWAYS use curly brackets for consistency's sake. Do many programmers do
        > this? Or is it pretty much a free for all?[/color]

        Do as you think it's better for you.
        Think that you'll have to read your code again in a few months time, and
        make it easy to identify what blocks (or instructions) 'belong' to what
        control structure.

        I tend to not use braces for most simple and direct "stuff":
        if ($bold) echo '<strong>';
        echo $content;
        if ($bold) echo '</strong>';

        but use them for things I might want to change later:
        // previous statement
        while ($row = mysql_fetch_row ($result)) {
        $option[] = $row[0];
        }
        // next statement

        this last one could very well be written as
        // previous statement

        //get db data
        while ($row = mysql_fetch_row ($result)) $option[] = $row[0];

        // next statement


        In the last two snippets I use blank lines and coments as shown. Of
        course the // next and // previous statement comments, in real code
        would be real statements (unless either was another thing I needed a
        comment for).
        --
        USENET would be a better place if everybody read: : mail address :
        http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
        http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
        http://www.expita.com/nomime.html : to 10K bytes :

        Comment

        • deko

          #5
          Re: curly brackets necessary in php?

          10-4

          Think I'll start with using them all the time and see how it goes from there.
          {
          Thanks for the tip :)
          }
          "Pedro Graca" <hexkid@hotpop. com> wrote in message
          news:c3j2mg$27o kta$1@ID-203069.news.uni-berlin.de...[color=blue]
          > deko wrote:[color=green]
          > > I'll have to admit, those curly brackets are a pain. But it would seem[/color][/color]
          better[color=blue][color=green]
          > > to ALWAYS use curly brackets for consistency's sake. Do many programmers do
          > > this? Or is it pretty much a free for all?[/color]
          >
          > Do as you think it's better for you.
          > Think that you'll have to read your code again in a few months time, and
          > make it easy to identify what blocks (or instructions) 'belong' to what
          > control structure.
          >
          > I tend to not use braces for most simple and direct "stuff":
          > if ($bold) echo '<strong>';
          > echo $content;
          > if ($bold) echo '</strong>';
          >
          > but use them for things I might want to change later:
          > // previous statement
          > while ($row = mysql_fetch_row ($result)) {
          > $option[] = $row[0];
          > }
          > // next statement
          >
          > this last one could very well be written as
          > // previous statement
          >
          > //get db data
          > while ($row = mysql_fetch_row ($result)) $option[] = $row[0];
          >
          > // next statement
          >
          >
          > In the last two snippets I use blank lines and coments as shown. Of
          > course the // next and // previous statement comments, in real code
          > would be real statements (unless either was another thing I needed a
          > comment for).
          > --
          > USENET would be a better place if everybody read: : mail address :
          > http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
          > http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
          > http://www.expita.com/nomime.html : to 10K bytes :[/color]


          Comment

          • Steve Holdoway

            #6
            Re: curly brackets necessary in php?

            Just to add on to what's been said...

            I always use braces, it makes the code much easier to read I find.
            Also, I use braces on separate lines as in

            if ( condition )
            {
            actions...
            }
            else
            {
            ....
            )

            Which I personally find easier to read. The use of one brace at the
            end of the condition line was started in an attempt to save paper when
            developing on teletypes and punched cards.

            Gives you some idea of how old I am (:

            Steve

            On Sun, 21 Mar 2004 04:39:28 GMT, "deko" <dje422@hotmail .com> wrote:
            [color=blue]
            >10-4
            >
            >Think I'll start with using them all the time and see how it goes from there.
            >{
            >Thanks for the tip :)
            >}
            >"Pedro Graca" <hexkid@hotpop. com> wrote in message
            >news:c3j2mg$27 okta$1@ID-203069.news.uni-berlin.de...[color=green]
            >> deko wrote:[color=darkred]
            >> > I'll have to admit, those curly brackets are a pain. But it would seem[/color][/color]
            >better[color=green][color=darkred]
            >> > to ALWAYS use curly brackets for consistency's sake. Do many programmers do
            >> > this? Or is it pretty much a free for all?[/color]
            >>
            >> Do as you think it's better for you.
            >> Think that you'll have to read your code again in a few months time, and
            >> make it easy to identify what blocks (or instructions) 'belong' to what
            >> control structure.
            >>
            >> I tend to not use braces for most simple and direct "stuff":
            >> if ($bold) echo '<strong>';
            >> echo $content;
            >> if ($bold) echo '</strong>';
            >>
            >> but use them for things I might want to change later:
            >> // previous statement
            >> while ($row = mysql_fetch_row ($result)) {
            >> $option[] = $row[0];
            >> }
            >> // next statement
            >>
            >> this last one could very well be written as
            >> // previous statement
            >>
            >> //get db data
            >> while ($row = mysql_fetch_row ($result)) $option[] = $row[0];
            >>
            >> // next statement
            >>
            >>
            >> In the last two snippets I use blank lines and coments as shown. Of
            >> course the // next and // previous statement comments, in real code
            >> would be real statements (unless either was another thing I needed a
            >> comment for).
            >> --
            >> USENET would be a better place if everybody read: : mail address :
            >> http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
            >> http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
            >> http://www.expita.com/nomime.html : to 10K bytes :[/color]
            >[/color]

            Comment

            • Sandman

              #7
              Re: curly brackets necessary in php?

              In article <Ti67c.40854$N6 1.35431@newssvr 25.news.prodigy .com>, "deko"
              <dje422@hotmail .com> wrote:
              [color=blue]
              > I'll have to admit, those curly brackets are a pain. But it would
              > seem better to ALWAYS use curly brackets for consistency's sake. Do
              > many programmers do this? Or is it pretty much a free for all?[/color]

              I always use them, unless it's a oneliner, like:

              if ($nr == 10) print "It's ten!";

              But I usually make them as compact as possible, with:

              if (condition){ print "foo"; }
              else { print "bar"; }

              And if the statements run more than one lines:

              if (condition){
              print "foo";
              $foo = true;
              } else {
              print "bar";
              }

              --
              Sandman[.net]

              Comment

              • Brandon Blackmoor

                #8
                Re: curly brackets necessary in php?

                deko wrote:[color=blue]
                > But it would seem better to ALWAYS use curly brackets
                > for consistency's sake.[/color]

                It is, for reasons of consistency, readability, and long-term
                maintainability .
                [color=blue]
                > Do many programmers do this?[/color]

                I do, and the people under me on my team do. I do not look kindly on
                people who generate error-prone code out of sheer laziness. Always use
                the brackets. Always. There is no excuse to leave them out.

                bblackmoor
                2004-03-21

                Comment

                • Brandon Blackmoor

                  #9
                  Re: curly brackets necessary in php?

                  Steve Holdoway wrote:[color=blue]
                  >
                  > Also, I use braces on separate lines as in
                  >
                  > if ( condition )
                  > {
                  > actions...
                  > }
                  > else
                  > {
                  > ....
                  > )[/color]

                  This is my preferred style, as well, and is the style mandated in our
                  coding guidelines. It makes the code more readable, and thus makes
                  errors less likely. It also makes searching for pairs of brackets much
                  easier.

                  bblackmoor
                  2004-03-21

                  Comment

                  • Chung Leong

                    #10
                    Re: curly brackets necessary in php?

                    Well, these's the alternative synatx:

                    if(IsMad($cows) ):
                    OrderTurkeyBurg ers();
                    CallCDC();
                    elsif(HasFlu($c hickens)):
                    OrderKungPaoBee f();
                    Cancel($trip_to _thailand);
                    else:
                    FireUpBBQ();
                    HaveUnprotected Sex();
                    endif;

                    for($i = 0; $i < 3; $i++):
                    ChangeRegime($a xis_of_evil[$i]);
                    endfor;

                    while($morale < 100):
                    ContinueBeating ();
                    endwhile;

                    ....etc.

                    In regular PHP code, this syntax is considered deprecated. Some of us like
                    to this it though when we place control structure within HTML. <? foreach(
                    .... )?> ... <? endforeach; ?> is much more readable than <? foreach( ... )
                    { ?> ... <? } ?> .

                    Uzytkownik "deko" <dje422@hotmail .com> napisal w wiadomosci
                    news:ar57c.4084 1$7J.38240@news svr25.news.prod igy.com...[color=blue]
                    >
                    > Do I need to use curly brackets in PHP if .. else statements? other[/color]
                    constructs?[color=blue]
                    > Does it matter? What are Best Practices? Why?
                    >
                    > thanks in advance...
                    >
                    > This seems to work WITHOUT curly brackets:
                    >
                    > if(ereg("Win", getenv("HTTP_US ER_AGENT")))
                    > $visos = "Windows";
                    > elseif((ereg("M ac", getenv("HTTP_US ER_AGENT"))) || (ereg("PPC",
                    > getenv("HTTP_US ER_AGENT"))))
                    > $visos = "Mac";
                    > elseif(ereg("Li nux", getenv("HTTP_US ER_AGENT")))
                    > $visos = "Linux";
                    > elseif(ereg("Fr eeBSD", getenv("HTTP_US ER_AGENT")))
                    > $visos = "FreeBSD";
                    > elseif(ereg("Su nOS", getenv("HTTP_US ER_AGENT")))
                    > $visos = "SunOS";
                    > elseif(ereg("IR IX", getenv("HTTP_US ER_AGENT")))
                    > $visos = "IRIX";
                    > elseif(ereg("Be OS", getenv("HTTP_US ER_AGENT")))
                    > $visos = "BeOS";
                    > elseif(ereg("OS/2", getenv("HTTP_US ER_AGENT")))
                    > $visos = "OS/2";
                    > elseif(ereg("AI X", getenv("HTTP_US ER_AGENT")))
                    > $visos = "AIX";
                    > else $visos = "unknown";
                    >
                    > And this seems to work WITH curly brackets:
                    >
                    > if (isset($_SERVER ))
                    > {
                    > if (isset($_SERVER["HTTP_X_FORWARD ED_FOR"]))
                    > {
                    > $visip = $_SERVER["HTTP_X_FORWARD ED_FOR"];
                    > }
                    > elseif (isset($_SERVER["HTTP_CLIENT_IP "]))
                    > {
                    > $visip = $_SERVER["HTTP_CLIENT_IP "];
                    > }
                    > else
                    > {
                    > $visip = $_SERVER["REMOTE_ADD R"];
                    > }
                    > }
                    > else
                    > {
                    > if (getenv('HTTP_X _FORWARDED_FOR' ))
                    > {
                    > $visip = getenv('HTTP_X_ FORWARDED_FOR') ;
                    > }
                    > elseif (getenv('HTTP_C LIENT_IP'))
                    > {
                    > $visip = getenv('HTTP_CL IENT_IP');
                    > }
                    > else
                    > {
                    > $visip = getenv('REMOTE_ ADDR');
                    > }
                    > }
                    >
                    >[/color]


                    Comment

                    • deko

                      #11
                      Re: curly brackets necessary in php?

                      yeah, that seems best to me as well. the trade off of screen space for
                      readability is well worth it.

                      "Brandon Blackmoor" <bblackmoor@spa mcop.net> wrote in message
                      news:c3l60b$24d t7a$2@ID-97660.news.uni-berlin.de...[color=blue]
                      > Steve Holdoway wrote:[color=green]
                      > >
                      > > Also, I use braces on separate lines as in
                      > >
                      > > if ( condition )
                      > > {
                      > > actions...
                      > > }
                      > > else
                      > > {
                      > > ....
                      > > )[/color]
                      >
                      > This is my preferred style, as well, and is the style mandated in our
                      > coding guidelines. It makes the code more readable, and thus makes
                      > errors less likely. It also makes searching for pairs of brackets much
                      > easier.
                      >
                      > bblackmoor
                      > 2004-03-21[/color]


                      Comment

                      • David Mackenzie

                        #12
                        Re: curly brackets necessary in php?

                        On Sun, 21 Mar 2004 15:05:37 +0100, Sandman <mr@sandman.net > wrote:
                        [color=blue]
                        >In article <Ti67c.40854$N6 1.35431@newssvr 25.news.prodigy .com>, "deko"
                        ><dje422@hotmai l.com> wrote:
                        >[color=green]
                        >> I'll have to admit, those curly brackets are a pain. But it would
                        >> seem better to ALWAYS use curly brackets for consistency's sake. Do
                        >> many programmers do this? Or is it pretty much a free for all?[/color]
                        >
                        >I always use them, unless it's a oneliner, like:
                        >
                        > if ($nr == 10) print "It's ten!";
                        >
                        >But I usually make them as compact as possible, with:
                        >
                        > if (condition){ print "foo"; }
                        > else { print "bar"; }[/color]

                        For simple stuff like this, you can usually use the ternary operator:

                        print( $nr == 10 ? "It's ten!" : "" );
                        print( condition ? "foo" : "bar" );

                        --
                        David ( @priz.co.uk )

                        Comment

                        • deko

                          #13
                          Re: curly brackets necessary in php?

                          thanks for the example. are my translations correct?
                          [color=blue]
                          > print( $nr == 10 ? "It's ten!" : "" );[/color]

                          if $nr is set to 10, then print "It's ten!", otherwise don't print anything
                          [color=blue]
                          > print( condition ? "foo" : "bar" );[/color]

                          if [some code] evaluates to "foo", then print "bar"

                          look ma, no curly braces!


                          Comment

                          • Mark Henning

                            #14
                            Re: curly brackets necessary in php?

                            > thanks for the example. are my translations correct?[color=blue]
                            >[color=green]
                            > > print( $nr == 10 ? "It's ten!" : "" );[/color]
                            >
                            > if $nr is set to 10, then print "It's ten!", otherwise don't print[/color]
                            anything[color=blue]
                            >[/color]

                            Yes.
                            [color=blue][color=green]
                            > > print( condition ? "foo" : "bar" );[/color]
                            >
                            > if [some code] evaluates to "foo", then print "bar"
                            >
                            > look ma, no curly braces!
                            >[/color]

                            No. If [some code] evalutates to true, print "foo" else print "bar".
                            It is equivelant to

                            if(condition)
                            print "foo"
                            else
                            print "bar"

                            The ternary operator works thusly:

                            (condition) ? if_true_do_this : if_false_do_thi s



                            Comment

                            • deko

                              #15
                              Re: curly brackets necessary in php?

                              > The ternary operator works thusly:[color=blue]
                              >
                              > (condition) ? if_true_do_this : if_false_do_thi s[/color]

                              10-4

                              just curious, does C++ use the same syntax?


                              Comment

                              Working...