Php echo if two conditions are true

PHP

In PHP, you can use the && (AND) operator with if statements to check if two conditions are both true. The code block executes only when both conditions evaluate to true if either condition is false, the block is skipped.

PHP also has an "and" keyword similar to &&, but it has lower precedence and can behave differently in complex expressions. It's recommended to use && for better clarity and consistency.

Basic Syntax

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

The code block executes only if both condition1 and condition2 are true. If any condition is false, execution skips the block entirely.

Example 1: Basic AND Logic

Here's how && works with different true/false combinations

<?php
if (true && true) {
    echo "true<br>";
} else {
    echo "false<br>";
}

if (true && false) {
    echo "true<br>";
} else {
    echo "false<br>";
}

if (false && true) {
    echo "true<br>";
} else {
    echo "false<br>";
}

if (false && false) {
    echo "true<br>";
} else {
    echo "false<br>";
}
?>
true
false
false
false

Only when both conditions are true does the output show "true". In all other cases, it shows "false".

Example 2: User Login Validation

A practical example checking username and password

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

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

Both conditions ($username == "admin" and $password == "12345") are true, so the login succeeds.

Example 3: Complex Conditions with Parentheses

Use parentheses to group conditions and avoid precedence issues

<?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.";
}
?>
You are eligible to vote.

The first condition ($age >= 18) is true, and the second condition ($country == "USA" || $country == "Canada") is also true, so both are satisfied.

Key Points

Operator Precedence Recommendation
&& Higher Preferred for clarity
and Lower Avoid in complex expressions

Conclusion

Use && to check multiple conditions in PHP if statements. Always use parentheses when combining AND and OR operators to ensure proper evaluation order and avoid unexpected behavior.

Updated on: 2026-03-15T10:45:26+05:30

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements