In this PHP tutorial, you will learn how to use OR operator in If-statement condition, and some example scenarios.

PHP If OR

PHP If condition can be compound condition. So, we can join multiple simple conditions with logical OR operator and use it as condition for PHP If statement.

If statement with OR operator in the condition

The typical usage of an If-statement with OR logical operator is

</>
Copy
if ( condition_1 || condition_2 ) {
  //if-block statement(s)
}

where

  • condition_1 and condition_2 can be simple conditional expressions or compound conditional expressions.
  • || is the logical OR operator in PHP. It takes two operands: condition_1 and condition_2.

Since we are using OR operator to combine the condition, PHP executes if-block if at least one of the condition_1 or condition_2 is true. If both the conditions are false, then PHP does not execute if-block statement(s).

Examples

1. Check if a is 2 or b is 5.

In this example, we will write an if statement with compound condition. The compound condition contains two simple conditions and these are joined by OR logical operator.

PHP Program

</>
Copy
<?php
$a = 2;
$b = 8;

if ( ( $a == 2 ) || ( $b == 5 ) ) {
    echo "a is 2 or b is 5.";
}
?>

Output

PHP If OR

2. Check if given string starts with “a” or “b”.

In this example we use OR operator to join two conditions. The first condition is that the string should start with "a" and the second condition is that the string should start with "b".

PHP Program

</>
Copy
<?php
$name = "apple";

if ( str_starts_with($name, "a") || str_starts_with($name, "b") ) {
    echo "$name starts with a or b.";
}
?>

Output

Second example of PHP If OR

Conclusion

In this PHP Tutorial, we learned how to write PHP If statement with AND logical operator.