linuxStat PHP Documentation
Conditional execution of PHP code
The PHP if statement provides a mechanism to execute
a block of PHP code only if a condition is true.
The if statement has the following structure:
if (condition 1) {
PHP Code 1
}
PHP Code 1 enclosed by the braces { } is executed
if condition 1 enclosed by the parentheses ( ) is TRUE.
If condition 1 is FALSE, PHP Code 1 is not executed.
Example 7.1:
I have 1005 Intel (INTC) shares in my Fidelity Investments
broker account.
I bought them at $18.05 a share. I keep track
of my profit or loss in a
PHP program using a variable named
$currentPrice. The value of this variable
is the current price of
1 share of Intel stock.
I use an if statement to determine when I am ready to sell my INTC shares.
$currentPrice = 17.80; // Line 1
if ($currentPrice < 18.05 ) { // Line 2
print "Do not take a loss. Do not sell your INTC shares. <br>";
}
Since the condition within the parenthess ( ) in Line 2 is TRUE,
the print statement is executed.
The program in Example 7.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>
<font size="5">
<?php
# An example of how PHP if statement works.
$currentPrice = 17.80;
if ($currentPrice < 18.05) {
print "Do not take a loss. Do not sell your INTC shares. <br>";
}
?>
</font>
</body>
</html>
Click the following link to execute the above PHP program
by my server's PHP interpreter.
Try the above example
Example 7.2:
$age = 9; // Line 1
if (($age > 12) && ($age <= 19)) { // Line 2
print "Marvin K. Mooney, you are a teenager. <br>";
}
Since the condition within the parenthess ( ) in Line 2 is FALSE,
the print statement is NOT executed.
The program in Example 7.2 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>
<font size="5">
<?php
# An example of how PHP if statement works.
$age = 9;
if (($age > 12) && ($age <= 19)) {
print "Marvin K. Mooney, you are a teenager. <br>";
}
?>
</font>
</body>
</html>
Click the following link to execute the above PHP program
by my server's PHP interpreter.
Try the above example Next Index