Conditions if, else, elseif, switch, foreach, while, for, etc.

Verze:

18. 06. 2025

Zodpovědná osoba:

Dominik Šlechta

Use elseif Instead of else if

  • Rule: The keyword elseif SHOULD be used instead of else if so that all control keywords look like single words.

  • Reason: Using elseif makes the code more consistent and readable by adhering to a single-word structure for the control flow keywords.

Example (Correct):

if ($a > 0) {
    // Do something
} elseif ($b > 0) {
    // Do something else
}

Example (Incorrect):

if ($a > 0) {
    // Do something
} else if ($b > 0) {
    // Do something else
}

Space Before and After Condition Expression

  • Rule: There MUST be one space before and after the condition expression in if, foreach, while, for, etc.

  • Reason: This improves readability by ensuring that conditions and their surrounding syntax are clearly separated.

Example (Correct):

if ($a > 0) {
    // Do something
}

for ($i = 0; $i < 10; $i++) {
    // Do something
}

Example (Incorrect):

if($a > 0){
    // Do something
}

for($i=0;$i<10;$i++){
    // Do something
}

Space After Every Semicolon in Loops

  • Rule: There MUST be one space after every semicolon in for loop declarations.

  • Reason: This makes the code more readable and consistent with standard coding practices.

Example (Correct):

for ($i = 0; $i < 10; $i++) {
    // Do something
}

Example (Incorrect):

for ($i=0;$i<10;$i++) {
    // Do something
}

Expressions in Parentheses Split Across Multiple Lines

  • Rule: Expressions in parentheses MAY be split across multiple lines, where each subsequent expression MUST be on the next line. The closing parenthesis and opening brace MUST be placed together on their own line with one space between them.

  • Reason: Splitting long expressions across multiple lines improves readability. Placing the closing parenthesis and opening brace together with one space helps maintain consistency in control structures.

Example:

if (
    $a > 0 &&
    $b < 10
) {
    // Do something
}

Conditions Must Have Opening and Closing Braces

  • Rule: Conditions (e.g., if, foreach, while, etc.) MUST have both opening and closing braces with the code between them.

  • Reason: This improves code clarity and prevents issues in the future, such as accidentally adding or removing code from the conditional block.

Example (Correct):

if ($a > 0) {
    // Do something
}

Example (Incorrect):

if ($a > 0)
    // Do something

Summary:

  • elseif SHOULD be used instead of else if for consistency.

  • One space must be placed before and after condition expressions.

  • One space must be placed after each semicolon in for loops.

  • Expressions in parentheses MAY be split across multiple lines with one space between the closing parenthesis and opening brace.

  • Opening and closing braces MUST be used in conditions, even if there is only one line of code in the block.