473,399 Members | 3,888 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

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_USER_AGENT")))
$visos = "Windows";
elseif((ereg("Mac", getenv("HTTP_USER_AGENT"))) || (ereg("PPC",
getenv("HTTP_USER_AGENT"))))
$visos = "Mac";
elseif(ereg("Linux", getenv("HTTP_USER_AGENT")))
$visos = "Linux";
elseif(ereg("FreeBSD", getenv("HTTP_USER_AGENT")))
$visos = "FreeBSD";
elseif(ereg("SunOS", getenv("HTTP_USER_AGENT")))
$visos = "SunOS";
elseif(ereg("IRIX", getenv("HTTP_USER_AGENT")))
$visos = "IRIX";
elseif(ereg("BeOS", getenv("HTTP_USER_AGENT")))
$visos = "BeOS";
elseif(ereg("OS/2", getenv("HTTP_USER_AGENT")))
$visos = "OS/2";
elseif(ereg("AIX", getenv("HTTP_USER_AGENT")))
$visos = "AIX";
else $visos = "unknown";

And this seems to work WITH curly brackets:

if (isset($_SERVER))
{
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
$visip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_CLIENT_IP"]))
{
$visip = $_SERVER["HTTP_CLIENT_IP"];
}
else
{
$visip = $_SERVER["REMOTE_ADDR"];
}
}
else
{
if (getenv('HTTP_X_FORWARDED_FOR'))
{
$visip = getenv('HTTP_X_FORWARDED_FOR');
}
elseif (getenv('HTTP_CLIENT_IP'))
{
$visip = getenv('HTTP_CLIENT_IP');
}
else
{
$visip = getenv('REMOTE_ADDR');
}
}
Jul 17 '05 #1
21 12913
On Sun, 21 Mar 2004 00:35:18 GMT, "deko" <dj****@hotmail.com> wrote:
Do I need to use curly brackets in PHP if .. else statements? other constructs?
Does it matter? What are Best Practices? Why?


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 <an**@andyh.co.uk> / Space: disk usage analysis tool
http://www.andyh.co.uk / http://www.andyhsoftware.co.uk/space
Jul 17 '05 #2
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" <an**@andyh.co.uk> wrote in message
news:di********************************@4ax.com...
On Sun, 21 Mar 2004 00:35:18 GMT, "deko" <dj****@hotmail.com> wrote:
Do I need to use curly brackets in PHP if .. else statements? other constructs?Does it matter? What are Best Practices? Why?


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 <an**@andyh.co.uk> / Space: disk usage analysis tool
http://www.andyh.co.uk / http://www.andyhsoftware.co.uk/space

Jul 17 '05 #3
deko wrote:
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?


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 :
Jul 17 '05 #4
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" <he****@hotpop.com> wrote in message
news:c3*************@ID-203069.news.uni-berlin.de...
deko wrote:
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?


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 :

Jul 17 '05 #5
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" <dj****@hotmail.com> wrote:
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" <he****@hotpop.com> wrote in message
news:c3*************@ID-203069.news.uni-berlin.de...
deko wrote:
> I'll have to admit, those curly brackets are a pain. But it would seembetter > to ALWAYS use curly brackets for consistency's sake. Do many programmers do
> this? Or is it pretty much a free for all?


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 :


Jul 17 '05 #6
In article <Ti*******************@newssvr25.news.prodigy.com> , "deko"
<dj****@hotmail.com> wrote:
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?


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]
Jul 17 '05 #7
deko wrote:
But it would seem better to ALWAYS use curly brackets
for consistency's sake.
It is, for reasons of consistency, readability, and long-term
maintainability.
Do many programmers do this?


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
Jul 17 '05 #8
Steve Holdoway wrote:

Also, I use braces on separate lines as in

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


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
Jul 17 '05 #9
Well, these's the alternative synatx:

if(IsMad($cows)):
OrderTurkeyBurgers();
CallCDC();
elsif(HasFlu($chickens)):
OrderKungPaoBeef();
Cancel($trip_to_thailand);
else:
FireUpBBQ();
HaveUnprotectedSex();
endif;

for($i = 0; $i < 3; $i++):
ChangeRegime($axis_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" <dj****@hotmail.com> napisal w wiadomosci
news:ar******************@newssvr25.news.prodigy.c om...

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_USER_AGENT")))
$visos = "Windows";
elseif((ereg("Mac", getenv("HTTP_USER_AGENT"))) || (ereg("PPC",
getenv("HTTP_USER_AGENT"))))
$visos = "Mac";
elseif(ereg("Linux", getenv("HTTP_USER_AGENT")))
$visos = "Linux";
elseif(ereg("FreeBSD", getenv("HTTP_USER_AGENT")))
$visos = "FreeBSD";
elseif(ereg("SunOS", getenv("HTTP_USER_AGENT")))
$visos = "SunOS";
elseif(ereg("IRIX", getenv("HTTP_USER_AGENT")))
$visos = "IRIX";
elseif(ereg("BeOS", getenv("HTTP_USER_AGENT")))
$visos = "BeOS";
elseif(ereg("OS/2", getenv("HTTP_USER_AGENT")))
$visos = "OS/2";
elseif(ereg("AIX", getenv("HTTP_USER_AGENT")))
$visos = "AIX";
else $visos = "unknown";

And this seems to work WITH curly brackets:

if (isset($_SERVER))
{
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
$visip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_CLIENT_IP"]))
{
$visip = $_SERVER["HTTP_CLIENT_IP"];
}
else
{
$visip = $_SERVER["REMOTE_ADDR"];
}
}
else
{
if (getenv('HTTP_X_FORWARDED_FOR'))
{
$visip = getenv('HTTP_X_FORWARDED_FOR');
}
elseif (getenv('HTTP_CLIENT_IP'))
{
$visip = getenv('HTTP_CLIENT_IP');
}
else
{
$visip = getenv('REMOTE_ADDR');
}
}

Jul 17 '05 #10
yeah, that seems best to me as well. the trade off of screen space for
readability is well worth it.

"Brandon Blackmoor" <bb********@spamcop.net> wrote in message
news:c3*************@ID-97660.news.uni-berlin.de...
Steve Holdoway wrote:

Also, I use braces on separate lines as in

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


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

Jul 17 '05 #11
On Sun, 21 Mar 2004 15:05:37 +0100, Sandman <mr@sandman.net> wrote:
In article <Ti*******************@newssvr25.news.prodigy.com> , "deko"
<dj****@hotmail.com> wrote:
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?


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"; }


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 )
Jul 17 '05 #12
thanks for the example. are my translations correct?
print( $nr == 10 ? "It's ten!" : "" );
if $nr is set to 10, then print "It's ten!", otherwise don't print anything
print( condition ? "foo" : "bar" );


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

look ma, no curly braces!
Jul 17 '05 #13
> thanks for the example. are my translations correct?
print( $nr == 10 ? "It's ten!" : "" );
if $nr is set to 10, then print "It's ten!", otherwise don't print

anything


Yes.
print( condition ? "foo" : "bar" );


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

look ma, no curly braces!


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_this

Jul 17 '05 #14
> The ternary operator works thusly:

(condition) ? if_true_do_this : if_false_do_this


10-4

just curious, does C++ use the same syntax?
Jul 17 '05 #15
> The ternary operator works thusly:

(condition) ? if_true_do_this : if_false_do_this


What if I want to *do nothing* if (condition) is false?

print( condition ? "foo" );

If [some code] evalutates to true, print "foo".

is this correct?
Jul 17 '05 #16
deko wrote:
What if I want to *do nothing* if (condition) is false?

print( condition ? "foo" );

If [some code] evalutates to true, print "foo".

is this correct?


What hapenned when you tried it? :)

--
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 :
Jul 17 '05 #17
In message <c3*************@ID-97660.news.uni-berlin.de>, Brandon
Blackmoor <bb********@spamcop.net> writes
Steve Holdoway wrote:
Also, I use braces on separate lines as in
if ( condition )
{
actions...
}
else
{
....
)
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.


I also use this, because of finding the pairs being easy, and almost
always use them even for a single statement as I agree with another
poster which is that it's too easy for humans to read the meaning from
the indentation instead of the brackets.
bblackmoor
2004-03-21


--
Five Cats
Email to: cats_spam at uk2 dot net
Jul 17 '05 #18
In message <K4********************@comcast.com>, Chung Leong
<ch***********@hotmail.com> writes
Well, these's the alternative synatx:

if(IsMad($cows)):
OrderTurkeyBurgers();
CallCDC();
elsif(HasFlu($chickens)):
OrderKungPaoBeef();
Cancel($trip_to_thailand);

<snip>

Good luck to those of you with good enough eyesight to spot the colons &
semi-colons in the above....
--
Five Cats
Email to: cats_spam at uk2 dot net
Jul 17 '05 #19
Five Cats wrote:
I agree with another poster which is that it's
too easy for humans to read the meaning from
the indentation instead of the brackets.


The problem with that is twofold: first, indentation can't be trusted to
remain in place. Even if the developers are wise enough to eschew tabs
and use spaces for indentation (and sadly, not all developers are this
wise), code *changes*. A few lines of code may be copied from one place
and pasted into another, and re-indented to fit with its new home. Or
perhaps it might be added to a nested control structure, or an
additional control structure might be added after the current
un-bracketed "if". All of this is simply an error waiting to happen.

Unless you are the only person who works on your code, and you never
touch it a second time after you type it, leaving the brackets out will
result in errors.

At least, that has been my observation.

bblackmoor
2004-03-22
Jul 17 '05 #20
In message <c3*************@ID-97660.news.uni-berlin.de>, Brandon
Blackmoor <bb********@spamcop.net> writes
Five Cats wrote:
I agree with another poster which is that it's
too easy for humans to read the meaning from
the indentation instead of the brackets.


The problem with that is twofold: first, indentation can't be trusted
to remain in place. Even if the developers are wise enough to eschew
tabs and use spaces for indentation (and sadly, not all developers are
this wise), code *changes*. A few lines of code may be copied from one
place and pasted into another, and re-indented to fit with its new
home. Or perhaps it might be added to a nested control structure, or an
additional control structure might be added after the current
un-bracketed "if". All of this is simply an error waiting to happen.

Unless you are the only person who works on your code, and you never
touch it a second time after you type it, leaving the brackets out will
result in errors.

At least, that has been my observation.


I think we are agreed that the brackets should be used.
--
Five Cats
Email to: cats_spam at uk2 dot net
Jul 17 '05 #21
In article <fl********************************@4ax.com>,
David Mackenzie <me@privacy.net> wrote:
On Sun, 21 Mar 2004 15:05:37 +0100, Sandman <mr@sandman.net> wrote:
In article <Ti*******************@newssvr25.news.prodigy.com> , "deko"
<dj****@hotmail.com> wrote:
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?


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"; }


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

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


I always use these when applicable, so perhaps I should have used this example:

if (condition){*print "foo"; }
else { $errors[]="Can't open file"; }

--
Sandman[.net]
Jul 17 '05 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Ken in Melbourne Australia | last post by:
If I use the curly bracket syntax (referred to as the complex syntax) within a string, how do I get to call a function within it? The php manual says that the first (or previous) character for...
1
by: inquirydog | last post by:
Hello- I, the inquirydog have a question: Using the AVT mechanism (curly brackets in an attribute value) is a great way to decrease the size of your xml document and make it more readable. Can...
6
by: STF | last post by:
While reading the C++ tutorial in this page: http://www.cplusplus.com/doc/tutorial/tut2-2.html I'm astonished to learn that we could omit curly brackets in function declaration for single...
4
by: lwoods | last post by:
In PHP you can do this: $x="test"; $y=$x{2}; echo $y; ....will display "s". Where in the PHP doc is this type of behavior for "curly brackets" defined?
2
by: Zain Homer | last post by:
Someone please let me know if I'm sending this to the wrong email alias... I'm wondering why we can't use the glob module to glob with curly brackets like we can from the command line (at least...
24
by: dmitrey | last post by:
Hi all, I looked to the PEPs & didn't find a proposition to remove brackets & commas for to make Python func call syntax caml- or tcl- like: instead of result = myfun(param1, myfun2(param5,...
3
by: Grande News | last post by:
Hi, I've got some PHP code that looks like this $cura= ord($data{$pnum*2}); $curb = ord($data{$pnum*2+1}); Notice the curly braces -- does using them make any difference, or will square...
37
by: dorayme | last post by:
Is there some particular reason that the inventors of CSS chose to leave us with the legacy of the curly brackets (for which one has to shift press) rather than the square (for which one simply...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.