PHP Echo If Two Conditions Are True



We use PHP if statement with && (AND) operator to check the two conditions. If both the conditions are true AND (&&) operator return true otherwise return false.

In PHP, we have an "and" keyword similar to the "&&" (AND) operator, but it has lower precedence than using an && (AND) operator. Therefore, it is best to avoid the "and" keyword for better clarity, and it also sometimes behaves differently in complex expressions.

Basic Syntax

if (condition1 && condition2) {
    echo "Both conditions are true!";
}

1) A block of code executes only if both condition 1 and condition 2 are true.
2) If any condition is false, then the code will stop to execute.
Write a PHP script that will echo some text if two conditions are true.

Example 1: True or false examples using &&

<?php
if (true && true) {
    echo "true&bsol;n";  // Output: true
} else {
    echo "false&bsol;n";
}

if (true && false) {
    echo "true&bsol;n";
} else {
    echo "false&bsol;n";  // Output: false
}

if (false && true) {
    echo "true&bsol;n";
} else {
    echo "false&bsol;n";  // Output: false
}

if (false && false) {
    echo "true&bsol;n";
} else {
    echo "false&bsol;n";  // Output: false
}
?>

Output

true
false
false
false

When both the conditions are true, the output is "true" otherwise "false".

Example 2: Checking Two Conditions for User Login

<?php
$username = "admin";
$password = "12345";

if ($username == "admin" && $password == "12345") {
    echo "Login successful!";
} else {
    echo "Invalid username or password.";
}
?>

output

Login successful!

Explanation

$username == "admin" ? true
$password == "12345" ? true
Since both conditions are true, it prints "Login successful!".

Example 3: Using Parentheses for Clarity

To avoid precedence issues, always use parentheses when combining conditions.

<?php
$age = 20;
$country = "USA";

if ($age >= 18 && ($country == "USA" || $country == "Canada")) {
    echo "You are eligible to vote.";
} else {
    echo "You are not eligible to vote.";
}
?>

Output

You are eligible to vote.

Explanation

age >= 18 (true)
country == "USA" or country == "Canada" (true)
Since both conditions are true, the message is printed.

Summar

  1. Use && (AND) to check if two conditions are true.
  2. Use parentheses () when combining AND (&&) and OR (||).
  3. If either condition is false, the if block does not execute.
  4. The "and" keyword also works like "&&", but has lower precedence, so && is preferred.
  5. Best practice: Always use && for better clarity and expected behavior.
Updated on: 2025-02-11T14:55:45+05:30

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements