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');
}
} 21 12944
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
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.c om... 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
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 :
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 :
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 :
In article <Ti************ *******@newssvr 25.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){*pr int "foo"; }
else { print "bar"; }
And if the statements run more than one lines:
if (condition){
print "foo";
$foo = true;
} else {
print "bar";
}
--
Sandman[.net]
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
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
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" <dj****@hotmail .com> napisal w wiadomosci
news:ar******** **********@news svr25.news.prod igy.com... 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'); } }
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 the curly bracket has to be a dollar sign '$'.
This is fine for variables, arrays and some objects but
doesn't allow me to call a function such as addslashes() or
trim() before I return the string in the variable.
|
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 one also
include the results of a call-template within curly brackets? Ideally
it would be great if you could just call the template as a function:
<tagname attributename="{mytemplate('abcd')}">
|
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 instruction as is written in the paragraph:
"statement is the function's body. It can be a single instruction or a
block of instructions. In the latter case it must be delimited by curly
brackets {}."
But I'm not sure if this is true. At least with...
|
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?
|
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 in tcsh). Is there a shell standard
for which the python glob module has been designed which
prevents the implimentation of the {}'s?
For example:
| |
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, param8), param3)
just make possible using
result = myfun param1 (myfun2 param5 param8) param3
it would reduce length of code lines and make them more readable, + no
needs to write annoing charecters.
|
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 brackets do the same thing?
Thanks
B
|
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
has to press)?
p
is two key presses shorter then
p {margin: 0;}
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |