linuxStat PHP Documentation

Conditional execution of PHP code

The PHP if-else statement provides a mechanism to execute
a block of PHP code only if a condition is TRUE and
to execute another block of PHP code if the condition is FALSE.
The if-else statement has the following structure:

if (condition 1) {
   PHP Code 1
}
else {
   PHP Code 2
}

The PHP code interpreter evaluates condition 1 enclosed
by the parentheses ( ) to determine if it is TRUE or FALSE.
PHP Code 1 enclosed by the braces { } is executed
if condition 1 is TRUE.
If the condition is FALSE then PHP Code 2 is executed.


Example 8.1:
$age = 15;                            // Line 1
if (($age > 12) && ($age <= 19)) {    // Line 2
   print "Marvin K. Mooney, you are a teenager. <br>"; // Line 3
}
else {
   print "Marvin K. Mooney, you are NOT a teenager. <br>";
}

Since the condition in Line 2 is TRUE, the print statement in Line 3
is executed.

The PHP program in Example 8.1 embedded in an HTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=us-ascii">
<title>Executed on Dell Server, Intel Processor, created on HP laptop</title>
</head>
<body bgcolor="#0F243E" text="#FFFF00" lang=EN-US>
<?php
# Example of how PHP if-else statement works.
$age = 15;
if (($age > 12) && ($age <= 19)) {
   print "Marvin K. Mooney, you are a teenager. <br>";
}
else {
   print "Marvin K. Mooney, you are NOT a teenager. <br>";
}
?>
</body>
</html>

Click the following link to execute the above PHP program
by my server's PHP interpreter.

Try the above example

Example 8.2:
$age = 9;                            // Line 1
if (($age > 12) && ($age <= 19)) {   // Line 2
   print "Marvin K. Mooney, you are a teenager. <br>";   // Line 3
}
else {
   print "Marvin K. Mooney, you are NOT a teenager. <br>";   // Line 4
}

Since the condition in Line 2 is FALSE, the print statement in Line 4
is executed.


The PHP program in Example 8.2 in an HTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=us-ascii">
<title>Executed on Dell Server, Intel Processor, created on HP laptop</title>
</head>
<body bgcolor="#0F243E" text="#FFFF00" lang=EN-US>
<?php
# Example of how PHP if-else statement works.
$age = 9;     
if (($age > 12) && ($age <= 19)) {
   print "Marvin K. Mooney, you are a teenager. <br>";
}
else {
   print "Marvin K. Mooney, you are NOT a teenager. <br>";
}
?>
</body>
</html>

Click the following link to execute the above PHP program
by my server's PHP interpreter.

Try the above example    Next    Index