
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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\n"; // Output: true } else { echo "false\n"; } if (true && false) { echo "true\n"; } else { echo "false\n"; // Output: false } if (false && true) { echo "true\n"; } else { echo "false\n"; // Output: false } if (false && false) { echo "true\n"; } else { echo "false\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
- Use && (AND) to check if two conditions are true.
- Use parentheses () when combining AND (&&) and OR (||).
- If either condition is false, the if block does not execute.
- The "and" keyword also works like "&&", but has lower precedence, so && is preferred.
- Best practice: Always use && for better clarity and expected behavior.