PHP if
In this chapter you will learn:
- What is an if statement
- Syntax for if statement
- Note for if statement
- Example - if statement
- Example - if statement with more conditions
Description
We can make simple Decisions with the if Statement.
Syntax
The basic form of an if construct is as follows:
if ( expression ) {
// Run this code /*from jav a 2 s . c o m*/
}
// More code here
If you only have one statement of code to execute, you can do without the braces entirely. It's a readability issue.
So, these two code chunks are the same:
if ($banned) {//from java2s.c o m
print "You are banned!";
}
if ($banned) print "You are banned!";
Note
If the expression inside the parentheses evaluates to true, the code between the braces is run.
If the expression evaluates to false, the code between the braces is skipped.
Example 1
Here is a working example for if statement:
<?php//from jav a2 s .c o m
$Age = 20;
if ($Age < 18) {
print "under 18\n";
} else {
print "You're not under 18\n";
}
?>
The code above generates the following result.
Example 2
Here's another example that uses the >= (greater than or equal) and <= (less than or equal) comparison operators, as well as the && (and) logical operator:
<?PHP/*from j a va 2 s .c o m*/
$myValue = 23;
if ( $myValue >= 10 && $myValue <= 20 ) {
echo "between 10 and 20.";
}
?>
Here's the previous example rewritten to use an if statement inside another if statement:
<?PHP//java 2 s .com
$myValue = 23;
if ( $myValue >= 10 ) {
if ( $myValue <= 20 ) {
echo "10 and 20.";
}
}
?>
Next chapter...
What you will learn in the next chapter:
- Description for if else statement
- Syntax for if else statement
- Note for if else statement
- Example - PHP if else statement
- Example - PHP if else statement ladder