PHP or operator (||) is a logical operator which allows more than operand, if one of these operands has a correct result, it will return true. if else, it will return false.

The following image shows you how it does work.

PHP Logical OR Operator

As you saw in the previous diagram, if only one way is correct, so it will return a true boolean result. That’s all.

The OR (||) logical operator can be written as the “OR” keyword or as the pipeline “||” symbol. So this operator can be written in the PHP code like the below expression.

Operand 1 || Operand 2
-- OR
Operand 1 or Operand 2

The following table shows you the cases of the two both operands and the expected result.

Operand 1Operand 2Or Operator Result (Operand 1 || Operand 2)
truetruetrue
falsefalsefalse
truefalsetrue
falsetruetrue

You know any operator can work inside if condition code structure, inline condition, or with a short expression. In the following sections, I will show you examples for each one.

Use the PHP OR (||) Logical Operator with the Short Expression

Actually, this way is used to assign or select the correct result to the PHP variable which will be in use in the following code scripts. Or just execute the correct result in something else. Let’s see the following examples.

<?php 
   $is_set_email = isset($_POST["email"]) || false;
   echo $is_set_email; // false
?>

In the example, I am looking for the true boolean value and searching for the email of the user input. So if it doesn’t exist, so it will show me a false value.

Otherwise, it will show me a true value like the below example.

<?php 
   $_POST["email"] = true;
   $is_set_email = isset($_POST["email"]) || false;
   echo $is_set_email; // true
?>

In the next section, I am going to explain the usage of the OR operator with the if condition.

Use the OR Operator with the IF Condition

The “if” condition is used to check about one or more two correct values, and here I will use it to check for the username using the OR operator.

<?php 
   $username = "CodedTag";
   if( ! isset( $username ) || $username === null || strlen( $username ) < 10 ) {
     echo "Invalid Username"; 
   }
?>

The previous example shows you only one condition is not achieved. And that was the character length of the – $username word. It was less than 10 letters, so it printed the – “Invalid Username” message.

Wrapping Up

The PHP OR operator would be written as – “OR“ or double pipe symbol – “||“. This operator returns only a true boolean value if one expression of two or many operands is true. Otherwise, it will show you a false value.

For a quick example.

<?php
  echo ( true || false ); // true
  echo ( true || true || false ); // true 
  echo ( false || false || true ); // true
  echo ( !false || true ); // true
  echo ( false || false ); // false
?>

That’s all. Thank you for reading. if you like to learn more about the PHP data types read this article. Stay tuned for my next tutorials.