Вы находитесь на странице: 1из 7

A Tour of Decision Making

Structures in PHP
by Timothy Boronczyk
2003-10-19

Synopsis
A comprehensive overview of the control structures available in PHP.

http://codewalkers.com/tutorials/52/1.html Page 1
A Tour of Decision Making Structures in PHP
by Timothy Boronczyk

Introduction
Often times, people find it difficult to make a decision--we're often asking ourselves
questions like, "What pair of pants should I wear to work?", "Should I really eat that
extra donut?" and "Should I tell my fiancee I wear a toupee?"
But computers have a much simpler life. Programs use logical comparisons to help
make a decision and depending on the value of the statement (whether it evaluates to
true or false) the program can process different sections of code.
A logical comparison compares the value of one operation or statement with that of
another to see if the overall statement resolves to either "true" or "false."
For example, if $x is set to 6, and $y is set to 7, then the statement "the value of $x is
less than the value of $y" is true. Statements saying $x's value is great than or equal
to the value of $y would be false.

Comparison Operators
The following chart shows some common operators you may use in your programs.

operator comparison
------------------------------------------------
x == y checks if the value of x is equal to
the value of y

x != y checks if the value of x is not


equal to the value of y

x < y checks if the value of x is less


than the value of y

x > y checks if the value of x is greater


than the value of y

x <= y checks if the value of x is less


than or equal to the value of y

x >= y checks if the value of x is greater


than or equal to the value of y

(a) && (b) checks if the value of statement a


and statement b evaluate to "true"

(a) || (b) checks if the value of statement a


or statement b evaluate to "true"

Let's apply that information to some example comparisons: Assuming $x holds the
value 5, $y holds 100 and $z holds 500:

http://codewalkers.com/tutorials/52/1.html Page 2
A Tour of Decision Making Structures in PHP
by Timothy Boronczyk

($x == $y) && ($x <= $z)


(5 == 100) && (5 <= 500)
false && true
> false

($x * $y) == $z
(5 * 100) == 500
500 == 500
> true

($x != $y) || ($y == $z)


(5 != 100) || (100 == 500)
true || false
> true

Be sure that you don't confuse = with ==. = assigns a value to a variable while ==
compares for equality. This can be a source of great frustration for many new
programmers until they become more accustomed to working with them.

IF Statements
Now let's examine a scenario in which a PHP script executes a section of code only if a
certain condition is met using an if-statement. An if-statement is made up of the
keyword if followed by the comparison surrounded by parentheses and then the lines
of code to be executed set apart by braces.

<?php
$x = 2;

echo "Hello, World.\n";


if ($x == 2)
{
echo "\$x = $x\n";
}
echo "Goodbye.\n";
?>

The script first assigns the value of 2 to $x and then prints a greeting message. The
logical comparison is made between $x and 2, which returns true. Because this
comparison evaluates to true, the script will process the code within the braces. The
script concludes by displaying a parting message.
If there's only one line of code to be executed under the conditional circumstance,
braces do not have to be used. So, the code could be re-written to resemble:

<?php
$x = 2;

http://codewalkers.com/tutorials/52/1.html Page 3
A Tour of Decision Making Structures in PHP
by Timothy Boronczyk

echo "Hello, World.\n";


if ($x == 2) echo "\$x = $x\n";
echo "Goodbye.\n";
?>

However, it is considered good practice and good form by the PEAR coding standards
to still use the braces.
IF-ELSE Statements
The if-statement only allows for a piece of code to be executed or skipped depending
on the return value of the comparison. But it can be extended with else to allow for an
alternate section of code to be processed.

<?php
$age = 25;

if ($age < 13)


{
echo "You are under 13.\n";
}
else
{
echo "You are 13 or over.\n";
}
?>

In this example, an if-statement checks to see if the value of $age is less than 13.
Because $age was assigned the value of 25, the first section of code is skipped and
the second section is executed, displaying the message "You are 13 or over."
Again, when only one line of code is used in a section then braces do not need to be
used... but it is considered good practice to use them anyway.

<?php
$age = 25;

if ($age < 13) echo "You are under 13.\n";


else echo "You are 13 or over.\n";
?>

Question-Colon Operator
A nice, compact way to write a short if-else statement is to use the ?: operator.
Because it uses symbols instead of keywords such as if and else, some may find it
difficult to start using and avoid it. However with some practice it does become easy to
use and can shorten the length of your code considerably.
The previous example can be written as follows:

http://codewalkers.com/tutorials/52/1.html Page 4
A Tour of Decision Making Structures in PHP
by Timothy Boronczyk

<?php
$age = 25;

echo ($age < 13) ? "You are under 13.\n" :


"You are 13 or over.\n";
?>

The first section of code (between the question-mark and the colon) will be used if the
conditional evaluates true. The second section of code (following the colon) will be
used if the evaluation is false. In the code, the statement ($age < 13) is tested and
returns false so "You are 13 or over." is displayed.
Typically, the ?: is seen when used to assign a value to a variable.

<?php
$a = 100;
$numbtype = ($a % 2 == 0) ? 'even' : 'odd';
echo "The number $a is $numbtype.\n";

// is equivalent to writing...

$a = 100;
if ($a % 2 == 0)
{
$numbtype = 'even';
}
else
{
$numbtype = 'odd';
}
echo "The number $a is $numbtype.\n";
?>

IF-ELSEIF Statements
Several conditional statements can be chained together using if-elseif statements.

<?php
$weather = 'rain';
echo "The weather forcast calls for $weather. ";
if ($weather == 'snow')
{
echo "You'd better bundle up!\n";
}
elseif ($weather == 'rain')
{
echo "Be sure to bring an umbrella!\n";
}
elseif ($weather == 'wind')
{
echo "Take the day off and fly a kite!\n";
}

http://codewalkers.com/tutorials/52/1.html Page 5
A Tour of Decision Making Structures in PHP
by Timothy Boronczyk

else
{
echo "So who knows what to expect?!\n";
}
?>

In the example, PHP will process the chain of if-elseif. Once the first true comparison
has been, PHP will execute the desired code block and then break out of the structure.
No further conditions of the structure are be tested.

SWITCH-CASE statements
As the ?: is an alternative to if-then statements, a switch-case statement provides a
cleaner way to code lengthy if-elseif statements where each test checks the same
variable for a specified value.

<?php
$weather = 'rain';
echo "The weather forcast calls for $weather. ";
switch ($weather)
{
case 'snow':
echo "You'd better bundle up!\n";
break;

case 'rain':
echo "Be sure to bring an umbrella!\n";
break;

case 'wind':
echo "Take the day off and fly a kite!\n";
break;

default:
echo "So who knows what to expect?!\n";
break;
}
?>

The comparison is made between the variable set by the switch and the values
designated by the case keyword. The code block of each case is terminated with
break. A default case can be used to execute a block of code if no other cases
returned a true comparison.
About the Author
Timothy Boronczyk lives in Syracuse, NY, where he works as an E-Services
Coordinator for a local credit union. He has a background in elementary education,
over 5 years experience in web design and has written tutorials on web design, PHP,
Ruby, XML and various other topics. His hobbies include photography and composing
music.

http://codewalkers.com/tutorials/52/1.html Page 6
A Tour of Decision Making Structures in PHP
by Timothy Boronczyk

Timothy Boronczyk lives in Syracuse, NY, where he works as an E-Services


Coordinator for a local credit union. He has a background in elementary education,
over 5 years experience in web design and has written tutorials on web design, PHP,
Ruby, XML and various other topics. His hobbies include photography and composing
music.

http://codewalkers.com/tutorials/52/1.html Page 7

Вам также может понравиться