I prefer putting logical operators in long if statements at the beginning of the line, mainly for readability and better behavior in version control.
Note that as also mentioned in the other answers it's usually a code smell to have long if statements. However sometimes you have to do it, or the code is already there and you can't rewrite it, so if it's already a bad thing then it helps not to make even more of a mess.
Also these things apply to if statements with just a single "and" where the different elements are so long you still need to split it to multiple lines (long variable or class names for instance).
if (
$something->getValue() === 'some_value'
|| (
$something instanceof SomeClass
&& $something->has($someNumber)
&& $someNumber > 42
)
) {
// do something
}
Readability: As all logical operators are vertically grouped you can instantly see which operator is on each line. As your eye scans the code it can just move straight vertically and it only needs to move horizontally when there is an actual extra logical level.
If the operators are at the end of the line your eye needs to move back and forth randomly between lines of uneven lenght.
Better behavior in version control: When an extra clause is added at the bottom of the if statement then this translates to 1 line added and 0 removed in version control.
diff --git a/3.php b/3.php
index 367c57c..2a40c3a 100644
--- a/3.php
+++ b/3.php
@@ -6,6 +6,7 @@
if (
$something instanceof SomeClass
&& $something->has($someNumber)
&& $someNumber > 42
+ && $anotherCase
) {
// do something
If you put logical operators at the end then that will be 2 lines added and 1 removed. That in turn obscures useful information: your commit message for the last change will be shown for both lines when you Git annotate, so you would have to go to the previous version to see the commit message for the line you added the operator to.
diff --git a/4.php b/4.php
index f654780..2b9e0c5 100644
--- a/4.php
+++ b/4.php
@@ -5,7 +5,8 @@
if (
$something instanceof SomeClass &&
$something->has($someNumber) &&
- $someNumber > 42
+ $someNumber > 42 &&
+ $anotherCase
) {
// do something