when using open and close brackets and when not [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I saw this piece of code which does not use a bracket or : before the if/else statement. I thought that every statement should start with { or :
What is the reason they do not use it here?
if (!$this->Article)
throw NotFoundException('Article');
// Set required permission.
$UserModel = new UserModel();
if ($this->Article->Status != ArticleModel::STATUS_PUBLISHED)
if (($this->Article->AttributionUserID == Gdn::Session()->UserID)
&& !$UserModel->CheckPermission($this->Article->AttributionUserID, 'Articles.Articles.Edit')
)
$this->Permission('Articles.Articles.View');
else
$this->Permission('Articles.Articles.Edit');
else
$this->Permission('Articles.Articles.View');

Please don't forget the edge case on calculating your code coverage with phpunit:
<?php
// Because it is "line based" and not statement base coverage
// one line will always have one coverage status
if (false) this_function_call_shows_up_as_covered();
// Due to how code coverage works internally these two lines are special.
// This line will show up as non executable
if (false)
// This line will show up as covered because it is actually the
// coverage of the if statement in the line above that gets shown here!
will_also_show_up_as_coveraged();
// To avoid this it is necessary that braces are used
if (false) {
this_call_will_never_show_up_as_covered();
}
?>
See https://phpunit.de/manual/current/en/code-coverage-analysis.html#code-coverage-analysis.edge-cases for more information.
Imo this is one reason why it is best practice to use always brackets, an other is, debugging such code you give as example is very annoying.

You use brackets to indicate to the interpreter where the if statement starts and stops. However, when the if statement only consists of one line, the brackets can be omitted and the interpreter conditionally executes (or not) the next line.
Whether or not this is a good practice is debatable.

If you have 2 or more operators in if statement always use brackets. If one operator, you can skip them.
But i suggest to always use brackets.

If the code that must to run in case the if statement returns true will have just a single line, you do not need the brackets. brackets in if statement are required just in case of more than one row of code inside it.

if the code between the "if" statement consists of one line you can get rid of bracket "{" but if the code of the "if" statement is consists of more than line you must use it

You can avoid the brackets when there is only one sentence to execute, or there is only one control statement... in this code:
if (!$this->Article)
throw NotFoundException('Article'); //Only one sentence
// Set required permission.
$UserModel = new UserModel();
if ($this->Article->Status != ArticleModel::STATUS_PUBLISHED)
//Insde there is only one if/else
if (($this->Article->AttributionUserID == Gdn::Session()->UserID)
&& !$UserModel->CheckPermission($this->Article->AttributionUserID, 'Articles.Articles.Edit')
)
//Inside there is only one sentence
$this->Permission('Articles.Articles.View');
else
//Else statement contains only one sentence
$this->Permission('Articles.Articles.Edit');
else
//Else statement contains only one sentence
$this->Permission('Articles.Articles.View');
In the first example if you want to execute 2 sentences, it must be enclosed in brackets like this:
if (!$this->Article)
{
$foo = true;
throw NotFoundException('Article');
}
Regards

Related

Should I end my PHP script with exit or exit;? [duplicate]

This question already has answers here:
Why is the semicolon optional in the last statement in php?
(3 answers)
Closed 6 years ago.
Today I have a little weird question.
Should I end my PHP script with exit or exit; and which is correct?.
Without ;
and
With ;
Thanks.
exit, exit;, exit(), and exit(); are exactly the same, but the fact is that you should not end your script with an exit() call, it's just bad practice (but it works).
EDIT
Clarifying why i said it's "bad practice", it's not about the functionality of "exit" itself, it's OK to halt the script execution if something bad happens, but the concept of "something bad" is really wide. In general, even if some unwanted condition occurs, the normal execution flow should reach to the end of the file. Just consider this example:
...some init stuff...
if (!user_is_authenticated) {
...print some nasty message...
exit();
}
...continue with normal stuff...
A better approach would be:
...some init stuff...
if (user_is_authenticated) {
...continue with normal stuff...
}
else {
...print some nasty message...
}
What's the difference? The difference is that in the second version you don't need to use exit(), which means if one day you need to do something after BOTH the "normal" and "unwanted" execution flows you can just add it at the end of the file.
It's more or less the same argument about why you should NOT use "return" in function bodies except at the end of the function..
It is allways a good practise to use semicolon
<?php
//exit program normally
exit;
exit();
exit(0);
//exit with an error code
exit(1);
exit(0376); //octal
?>
Like Johnny said, all those four forms of 'exit' statement work. Both exit and exit() work if there is no statements followed by any of these two language constructs. It doesn't work if there is any other PHP statements followed by these two constructs and semicolon's purpose is to end the statement to proceed to the next statement, therefore you need to use exit; or exit(); to avoid syntax error and also, in this case, without using semicolon is considered to be a bad practice in the coding conventions.

PHP - If statement always evaluating as true? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So I can't get my head around this if statement.
What I am trying to do is get the person logged in from $_SESSION["user_name"] and if it matches one of two possible "admin" users, to give extra functionality. But it's always firing true.
For the example I'm going to have three users: Emma, John and Robert. Emma and John should be allowed the extra "admin functionality", but Robert is not allowed it. So...
My statement is:
if ($_SESSION["user_name"] === "emma" or "john"){
//give extra functionality as well as basic functionality
} else {
//give just basic functionality
But this is always firing true, so when I log in as my test account with the username Robert, he is also getting the extra functionality.
I've tried changing the quotation marks " of $_SESSION to apostrophes ', and also tried changing the operator from === to ==. I even tried = but found the hard way that this was setting my $_SESSION variable to "emma".
What am I doing wrong because I just can't seem to get my head around it?
If it's worth noting, this if statement is contained in a parent if statement that uses colons : and endif rather than brackets {}. The parent if statement is purely there to decide on what functionality to output based a column returned being empty or a user's name in there.
You need to redeclare the full condition:
if ($_SESSION["user_name"] === "emma" or $_SESSION["user_name"] === "john"){
//give extra functionality as well as basic functionality
} else {
...
}
Update With Explanation:
The pseudo code syntax for if statements is:
if ([some condition] [and/or] [another condition]) {
// then do some stuff
}
each of those [condition] statements is evaluated as either "truthy" or "falsey". So your original question could be re-written something like this:
if ([$_SESSION["user_name"] is equal to "emma"] or ["john" is not false, 0, or null]) {
// we will always get in here
}
Since "john" will always be "truthy" (it is not false, null, 0) it will always pass the condition.
The term "john" as an expression is true:
if ( "john" )
will evaluate to true and not throwing any syntax errors.
What you want is:
if ($_SESSION["user_name"] === "emma" || $_SESSION["user_name"] === "john") {
It may help to break this into steps. PHP will evaluate everything to the left of or to see if it's true or false. Then it will evaluate what's on the right of the or.
Turns out, "john" evaluates to true.
You're looking for:
if ($_SESSION["user_name"] === "emma" or $_SESSION["user_name"] === "john") {
Try something like this
if (($_SESSION["user_name"] === "emma") || ($_SESSION["user_name"] === "john"))
{
//do something
}
else
{
//other thing
}

if($_GET['info'] ==...) not checking [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I wrote a little check to display succes messages whenever a form is validated succesfully. However the check I use doesn't work. it doesn't matter what $_GET['info'] is, it just shows all messages unless $_GET['info] is empty. so even when info = loggin it shows all three messages. any help?
if(!empty($_GET['info'])){
if($_GET['info'] == "succes-paid"){
echo "<p class='succes'>De bestelling/inschrijving is succesvol verlopen.</p>";
}
if($_GET['info'] == "succes-register"){
echo "<p class='succes'>U werd succesvol geregistreerd.</p>";
}
if($_GET['info'] == "login"){
echo "<p class='succes'>U werd succesvol ingelogd.</p>";
}
}
You have a semi-colon after each of your if statements. The semi-colon means "finish the statement". Therefore your program thinks that you are done with the if and everything in your braces is treated as a block separate from your if statement. That is why those blocks are always executing.
It's because of the semicolon right after the condition of the if.
That line is actually two statements. The first is the if with condition, followed by an 'empty' statement, ended by a semi-colon. The second is a compound statement (a block of statements within a set of { .. }. The compound statement doesn't have a condition at all, so it is always executed.
if($_GET['info'] == "succes-paid") ; {echo 'x'}
condition with no statement -----^ ^ ^--------^-- compound statement without condition
\_The semi-colon that separates them.
And you have this situation three times, hence three lines of output.

Is it normal practice to use variables to store parameter data? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In some examples of PHP, I see people assign things to shorthand variables, and then use the shorthand variables instead. Is this common practice? Is this good practice?
$name = $_POST['name'];
and then they use they use $name down here to echo it or use it as a function parameter.
Another example is:
DEFINE('DB_USER', 'username');
mysqli_connect(DB_USER.......);
Pros:
Shorthand variables can be easier to type and remember.
A shorthand variable might allow an expensive operation to be done once instead of repeated many times. But beware of premature optimization! Most of the time this sort of optimization would be premature.
A shorthand variable can be used to make a copy that can be changed without modifying the original variable.
In some languages, a shorthand variable can be used to make a copy that is guaranteed to persist even if the the original variable is modified.
Cons:
Indiscriminate use of shorthand variables can result in multiple names for the same values.
In some languages and situations, a shorthand variable will make an unnecessary copy, using additional resources.
I have been doing php professionally for about 5 years now.
Usually when getting post variables it is a good idea, but even more common is to wrap it in an isset ternary if statement:
$name = isset($_POST['name']) ? $_POST['name'] : false;
This way if the variable isn't passed then you don't get an undefined variable warning.
Further, it saves you having to type $_POST every time, and it helps encapsulate the code a bit better.
The most important thing when writing code is writing readable code, not just for others but also for yourself. We do this all the time, i.e. abstracting and applying oo methods of programming.
So predefining the variables we'll be using and setting defaults makes perfect sense.
I would do something like this...
class ValueTooLong extends Exception {}
function R($param, $default=null, $type='string', $max_length=null) {
if(!isset($_REQUEST[$param]))
return $default;
$r = $_REQUEST[$param];
if($max_length && strlen($r) > $max_length)
throw new ValueTooLong('Length of '.$param.' was '.strlen($r).'. Max length is: '.$max_length);
if($type === 'bool' || $type === 'boolean') {
if($r === 'false' || $r === 'no')
return false;
return !empty($r);
}
settype($r, $type);
return $r;
}
# Which allows me do do this:
$name = R('name');
# or:
$count = R('count', 1, 'int');
EDIT: Function now takes a max_length parameter (as suggested by comment) and throws an exception if value of request parameter is too long

PHP if statement does not work [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have written a code where a value is got from mysql and if it is 1 then row should be in red colour and if it is 0 the row should be in green colour. When I execute the code it always goes to the else statement.
Code is as below:
while ($row = mysqli_fetch_array($result))
{
$bprofit=$row['profit_loss'];
if ($bprofit == "1") {
$colour='#FF0000';
} else {
$colour='#31B404';
}
echo "<tr bgcolor=$colour>";
echo "<td>" . $bprofit . "</td>";
}
and output is:
1
0
0
all in green colour only.
Any suggestions?
You have an extra p in $bpprofit:
if ($bprofit == "1")
change if ($bpprofit == "1") to if ($bprofit == "1")
In addition to the misspelling mentioned in other answers, I think you need to reference the first index of the array like so:
if ($bprofit[0] == "1") ...
EDIT
Based on your new code, are you sure the value that is being returned is a string and not numeric? If it is numeric, you would want your if statement to look like this:
if ($bprofit == 1) ...
In situations like this it never hurts to use var_dump() function and see what the variable actually contains and how you need to access it.
When encountering problems such as the one above, try activating error reporting in PHP. One way to do this is to update php.ini, but since this might affect other projects in which you don't want error reporting, it might be better to activate it when needed.
What's important is that you enable reporting of notices, since they'll appear when you use a variable that hasn't been set.
The code below is a simple example:
<?php error_reporting(E_ALL);
if ($undefined == 1) {
// do stuff
}
When this page is displayed, a notice will be shown:
Notice: Undefined variable: undefined in
/var/www/test/undefined_example.php on line 3
Of course, this might not be a suitable solution for all problems, but it might help you figure out where to look.
It might also make you a better programmer; by "reminding" you to declare variables with a standard value if they are not always assigned before later use.

Categories