...

View Full Version : Does a multiline IF() statement NEED curly braces??



mOrloff
02-04-2010, 11:06 PM
I came across this code, and I'm wondering whether the {} (or lack there of) are optional?
Is this clip (a direct copy&paste)

$fp = fopen('records_all_fields_truncated.csv', 'r');
if (!fp)

$i=0;
while (($data = fgetcsv($fp, 1000, ",")) != FALSE)
{
$data00 = str_replace("'","",$data[1]);
$data11 = str_replace("'","",$data[2]);
$data33 = str_replace("'","",$data[4]);
$data55 = str_replace("'","",$data[6]);
...

equivalent to

$fp = fopen('records_all_fields_truncated.csv', 'r');
if (!fp)
{ // ## Curly-brace added here ##
$i=0;
while (($data = fgetcsv($fp, 1000, ",")) != FALSE)
{
$data00 = str_replace("'","",$data[1]);
$data11 = str_replace("'","",$data[2]);
...
} // ## Curly-brace added here ##


I thought it would need them if it went into multiple lines.
Yes? No? Maybe So?
~ Mo

Fou-Lu
02-04-2010, 11:35 PM
Curly braces are required for multiple line processing.
The blocks are not equivilent; the first example is an error.
Hmm, under the assumption that whitespace is ignored, the first block will only set $i = 0 if it could not open the file. Both are incorrect though, as this is specifically indicating an if block for if the file could not be opened yet uses the $fp as a valid file pointer.

mOrloff
02-05-2010, 12:04 AM
Thanks.

My initial suspicion was that the developer must have changed his mind on how he wanted to do things, and left an artifact.
But then I started second-guessing myself. :rolleyes:

Based on how I understand what you're saying, I should have gone with my gut. :)

~ Mo

MattF
02-05-2010, 12:17 AM
That's it's braced equivalent.


$fp = fopen('records_all_fields_truncated.csv', 'r');
if (!fp)
{
$i=0;
}

while (($data = fgetcsv($fp, 1000, ",")) != FALSE)
{
$data00 = str_replace("'","",$data[1]);
$data11 = str_replace("'","",$data[2]);
$data33 = str_replace("'","",$data[4]);
$data55 = str_replace("'","",$data[6]);
...

Fou-Lu
02-05-2010, 05:32 AM
Still no validation, this would be probably what is intended:


if ($fp = fopen('records_all_fields_truncated.csv', 'r'))
{
$i = 0;
while (($data = fgetcsv($fp, 1000, ",")) != FALSE)
....
}

$fp needs to be a file pointer, or the fgetcsv could fail.

But yes, according to the initial block, MattF's code is what it should be. Thats why I was saying that both are improper.

Lol, just noticed that we're treating the $fp as a FILE *, so it should be if (!$fp) instead of if (!fp).

abduraooft
02-05-2010, 10:26 AM
btw,

if(some-condition)
while(condition){
..........
..........

} is equivalent to



if(some-condition){
while(condition){
..........
..........

}
}. However, putting the curly braces after if is a good practice in similar situations.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum