I need to know if I'am allowed to use single row if-statements according to the PSR-2 Coding Style.
I've already read the docs but i couldn't find any information about that.
https://www.php-fig.org/psr/psr-1/
https://www.php-fig.org/psr/psr-2/
<?php
// This is fine
if ($expr)
{
echo $expr;
}
// This also?
if ($expr) { echo $expr; }
?>
no, there is clearly said:
"An if structure looks like the following. Note the placement of parentheses, spaces, and braces; and that else and elseif are on the same line as the closing brace from the earlier body."
https://www.php-fig.org/psr/psr-2/#51-if-elseif-else
So 1st variant is OK, 2nd isn't.
P.S Actually 2nd case look OK in your example, but in case of bigger conditions, in real life it is less readable, so we need to obey singular 1st approach
For logical and faster purposes, whenever you make PHP try two statements using an AND condition, if the first one fails he doesn't attempt to try the second one... for logical and faster purposes that is beautiful indeed, but on my case I would need to know if the second statement also didn't work, so I don't need to make an user go through the same page a lot of times because the mistake was different than before...
So, assuming I have this:
if ($firstModel->validate() && $secondModel->validate()) {$sayCheese;}
How do I make it try both?
I did consider separating the models but I just want to know if there's an alternative.
Edit:
My form has multiple inserts for different models at the same time so the validation works beautifully if for a single model only, and since I need to try two or more at the same time, NOT stopping at the first statement is a MUST.
if ($firstTry & $thenTry) {$sayCheese;}
This will do a bitwise and, and check $thenTry even if $firstTry is false.
Edit : note I am just naively replying to your question, but I am not entirely sure why you would realistically want to do this.
You should consider to split the checks and your if-condition
$firstTry = checkOne();
$thenTry = checkTwo();
if ($firstTry && $thenTry) {
echo $sayCheese;
} else {
echo "check 1: ".($firstTry ? 'ok' : 'bad')."<br>";
echo "check 2: ".($firstTry ? 'ok' : 'bad')."<br>";
}
I've got a question about isset() with multiple conditionals, and checking to make sure they return non-null or correct results.
I'm trying to troubleshoot an isset expression that looks like:
if(isset($content['field_1']) && $content['field_2'] && $content['field_3']=="top"){
do a thing
}
I understand that if field_1 is true, then the other conditionals are treated as true.
My "if" statement is looped thorugh a few times as a slideshow is being created.
Most of the slide created have all true resuults and are fine, but there are a couple slides where the value exists but not exactly as required.
The code works, but the drupal error log gets filled warnings of "undefined index".
The question I have is:
What is the best way to have a multiple conditional isset while proofing each section?
a simple "else" after the "if" isn't solving this since it's multiple conditionals (I think). and I don't know if there is an easier way to handle this than breaking the multiple conditionals into single ones before continuing.
If anyone kind enough to read this has questions, or if my question is not clear pelase let me know. I'm happy to clarify.
Thanks!
I understand that if field_1 is true, then the other conditionals are treated as true.
Your assumption is wrong. You do not check value of $content referenced by key field_1, you check if such key exsits - these are two different things. Also you use && (AND) operator, and in such case if one condition returns false then evaluating remaining is pointless as by the boolean logic the whole expression will be false.
try this:
if ((!empty($content['field_1']) || !empty($content['field_2'])) && !empty($content['field_3']) && $content['field_3'] == 'top') {
// Do Something
}
I've never been a fan of brackets in control structures and only today I realised how it only accepts one statement within a bracket less if condition, if I have more than one statement it will throw a syntax error. Is this how PHP works or can it be something wrong with my IDE?
Obviously the error is clear but I just want to make sure this is normal.
If you have any other any links to other alternate syntax let me know please.
Bellow is just something I pasted from a project am doing and example of the syntax error.
if($this->reel3 = 1)
parent::addCash($this->$bet*2);
print(parent::getCash()); // < Line throwing the syntax error
else
// TODO
EDIT (FURTHERMORE)
After looking at some of the answer and comments I was wondering how its done in a professional environment, I know this is more about taste but I want to know from the professional out there if the style of the syntax matters?
Would
if(condition)
{
//something
} else {
//something
}
be better than
if(condition):
//something
else:
//something
endif;
or any other way of writing the same piece of code?
This is how php works. If you don't put brackets around your if statement only the next statement is in the if block all other follow up statements are outside of it. But since you have a else block after it you will get a error.
(BTW: You make an assignment in the if block, so this will be always true)
Look at these 2 examples:
if($this->reel3 = 1)
parent::addCash($this->$bet*2); //In the if statement
print(parent::getCash()); //Outside the if statement
else
Same as:
if($this->reel3 = 1) {
parent::addCash($this->$bet*2);
}
print(parent::getCash());
//^^^^^ I think here it's more clear to see that this will give you a error, since it's between the if and else block which is not allowed
else { }
For more information about the control structure if see the manual: http://php.net/manual/en/control-structures.if.php
Take a look at the answer of this question:
PHP conditionals, brackets needed?
And yes, it is PHP, not your IDE!
This is perfectly normal of all programming languages that use brackets rather than indentation to designate blocks of code. Without the brackets, there is no way for the interpreter to know which lines are part of the if block and which aren't. The one-line if-block is a convenient shortcut: if you don't include any brackets, PHP like many other languages will treat the single line directly following the if statement as the body of the if block.
Note PHP does have an alternative syntax for if statements as well, using colons instead of brackets, but that's a story for another day.
if (condition) { /* do something */ }
else { /* do something */ }
if (condition)
/* do something */
else
/* do something */
I was told that the first instance wasn't a good idea. I have no idea whether this is really this case (or for the second one either); does it not shorten the amount to type? Or is it because it just makes a mess?
The best practice is to write code that others can read and update easily.
Your first form is questionable because it doesn't follow the forms that most PHP developers are used to:
if (condition) {
// code
} else {
// code
}
// ... or ...
if (condition)
{
// code
}
else
{
// code
}
// ... or ...
if (condition) { /* short code */ } else { /* short code */ }
// ... or ...
condition ? /* short code */ : /* short code */;
Note that this is entirely about standard practice, and doesn't necessarily make senseāit's only about what other developers are used to seeing.
Your second form, more importantly, isn't so good because it makes it easy for another programmer to make this mistake:
if (condition)
// code A
else
// code B
// code C (added by another programmer)
In this example, the other programmer added code C, but forgot to wrap the whole else block in braces. This will cause problems. You can defend against this by simply wrapping your if and else blocks in braces.
My preference if for consistency... so:
if(...)
{
statement 1;
statement 2;
}
else
{
statement 1;
statement 2;
}
is no different than:
if(...)
{
statement 1;
}
else
{
statement 1;
}
So I always use them because it is consistent and it avoids problems forgetting to add them in later.
However other people will look at my code and think that it is stupid to put in the { and }. They have their reasons, I have mine... I happen to like my reasons more than I like theirs :-)
Generally non-readable code is a bad practice. The single line is more efficient in your typing and saves line numbers but come back to it a year from now or while you're scanning for bugs and it'll make it more difficult.
In my opinion, yes it's bad practice to have single line if statements.
The computer doesn't really care (as far as I can tell) but you should always write your code like it's going to be maintained by a serial killer that knows where you live.
Readable! Easily self-discernable.
The problem I've seen is developers not recognizing the {}-less-if when they add code to one of the conditions. Example:
//before
if(something)
statement;
//after
if(something)
statement;
addedstatement;
Obviously, this won't do what they expect.
Have you ever seen code like this in C or C++?
/* Warning: bogus C code! */
if (some condition)
if (another condition)
do_something(fancy);
else
this_sucks(badluck);
Either the indentation is wrong, or the program is buggy, because an "else" always applies to the nearest "if", unless you use braces.
(Let's just use python. No brackets, just pure clean whitespaces. :P)
For all but the shortest statements, use the braces and space them accordingly. You want to do this for a few reasons:
It's harder to make a mistake about where something goes.
It's easier to read.
In languages with macro-expansion facilities (e.g. C, C++), failure to include braces will cause confusing logic errors when a macro containing multiple statements is expanded inside of an unbraced if-else.
One major benefit of using multiple lines is ease of debugging. If you have an if else statement all on one line and the debugger tells you that line x blew up, it's more difficult to determine which part of the statement failed. Multiple lines also makes it easier to step through your code using a debugger.
Those are two lines long, so not really a single line.
There's nothing wrong with single line ifs when it makes the code easier to read.
For example, something like this:
if (last_item) print ", and " else print ", "
is much better than
if (last_iem)
{
print ", and "
}
else
{
print ", "
}
This is more coding style than anything else. That said, my personal opinion is that your second example is potentially quite harmful. It's easy enough to accidentally "add a second line to the block" in languages where braces are the only way to create blocks. But in PHP, where an alternate syntax exists, this is even less likely to set off the necessary warning bells:
if ($_GET["asdf"]==1):
/* do something */
else:
/* do something */
endif;
Rule of thumb: if you're going to put your "do something" on a separate line, use braces; if you're not going to use braces, put it on the same line!
I have seen so many third party code with silly issues, that I prefer to use braces all the time. That said I have never felt good on
if(){}
else (){}
I use if(){} on the same line when it is a short instruction and it is alone. If there is an else use the long:
if(checkSomething)
{
//dosomething
}
else
{
//doanotherthing
}
This is something that I actually remember from an employment exam a while back. The code was similar to the following:
if (x == 0)
x = 2;
else
print("x is: %d", x); // debugging!
x = 4;
Most people here can spot the error, but you can really substitute in anything you want as the "bad code" that was inserted. The more subtle error comes when you have an "old version" of something commented out, and somebody un-comments it, and suddenly the second statement is outside the block.
Basically, unless it's a small test application to learn a concept fast, I always bracket (and even in the test apps I usually bracket). It just isn't worth the headache later if I don't, even in 5-line-methods.
You should put the "if" and the "do something" on separate lines to make your code friendlier to interactive debuggers.
If you put both the "if" and "do something" on the same line, then you can't set a breakpoint just on the "do something" line.