Low cost ecommerce web development India flash website design

Control Structures

All the examples of PHP code that we've seen so far have been either simple, onestatement

scripts that output a string of text to the Web page, or have been series

of statements that were to be executed one after the other in order. If you've ever

written programs in any other languages (be they JavaScript, C, or BASIC) you

already know that practical programs are rarely so simple.

PHP, just like any other programming language, provides facilities that allow us

to affect the flow of control in a script. That is, the language contains special

statements that permit you to deviate from the one-after-another execution order

that has dominated our examples so far. Such statements are called control

structures. Don't get it? Don't worry! A few examples will illustrate perfectly.

The most basic, and most often-used, control structure is the if-else statement.

Here's what it looks like:

if ( condition ) {

// Statement(s) to be executed if

// condition is true.

} else {

3$_REQUEST is not available in versions of PHP prior to PHP 4.1.

59

Control Structures

// (Optional) Statement(s) to be

// executed if condition is false.

}

This control structure lets us tell PHP to execute one set of statements or another,

depending on whether some condition is true or false. If you'll indulge my vanity

for a moment, here's an example that shows a twist on the welcome1.php file we

created earlier:

$name = $_REQUEST['name'];

if ( $name == 'Kevin' ) {

echo( 'Welcome, oh glorious leader!' );

} else {

echo( "Welcome, $name!" );

}

Now, if the name variable passed to the page has a value of Kevin, a special message

will be displayed. Otherwise, the normal message will be displayed and will

contain the name that the user entered.

As indicated in the code structure above, the else clause (that part of the ifelse

statement that says what to do if the condition is false) is optional. Let's

say you wanted to display the special message above only if the appropriate name

was entered, but otherwise, you didn't want to display any message. Here's how

the code would look:

$name = $_REQUEST['name'];

if ( $name == 'Kevin' ) {

echo( 'Welcome, oh glorious leader!' );

}

The == used in the condition above is the PHP equal-to operator that's used to

compare two values to see whether they're equal.

website designer freelance ASP PHP ecommerce web developer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110