PHP if Statement
In this page:
Basic if Statement
An if statement runs its block only when the condition inside the parentheses evaluates to true; if it's false, PHP skips the entire block and moves straight to whatever comes after it — no error, no output, just silently continuing execution.
Example: Basic if Statement
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
?>
Login to try C/C++/Java/PHP code in the editor
Comparison inside Conditions
=== compares both value and type without any automatic conversion, which makes it the safer default inside an if condition — if ($status === active) won't accidentally match 1 or "1" the way the looser == operator sometimes can.
Example: Comparison inside Conditions
<?php
$status = "active";
if ($status === 'active') {
echo "Status is active.";
}
?>
Login to try C/C++/Java/PHP code in the editor
Logical AND (&&) in Conditions
&& inside a condition requires every joined expression to be true before the block runs — if ($age >= 18 && $hasConsent) only executes when both checks pass, which is exactly the pattern for enforcing multiple independent requirements at once.
Example: Logical AND (&&) in Conditions
<?php
$age = 20;
$hasConsent = true;
if ($age >= 18 && $hasConsent) {
echo "Access granted.";
}
?>
Login to try C/C++/Java/PHP code in the editor
Logical OR (||) in Conditions
|| inside a condition lets the block run if *any* one of the joined expressions is true, which suits situations with several acceptable paths to the same outcome — like accepting a login from either a username or an email address.
Example: Logical OR (||) in Conditions
<?php
$username = "";
$email = "[email protected]";
if ($username || $email) {
echo "Login accepted.";
}
?>
Login to try C/C++/Java/PHP code in the editor
Nested if Statements
Placing one if inside another lets you check a second condition only once the first has already passed — useful when the second check genuinely only makes sense in that context (checking a file's contents, say, only after confirming the file exists at all).
Example: Nested if Statements
<?php
$fileExists = true;
if ($fileExists) {
$content = "sample data";
if (!empty($content)) {
echo "File exists and has content.";
}
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: