DJ Mike's Tutorials: PHP

Conditional Statements


< ^ >

Else Clause and Elseif Clause


An If statement performs a test and executes a block of code if the test returns true. An else clause and a elseif clause are optional parts of an if statement that hold blocks of code to be executed if the if statement returns false.

Else

The syntax for an else clause is:

if ( test )
{ block of code executed if test returns true }
else
{ block of code executed if test returns true }


To see an example, let's look at another way to do a password check:


Show Code | Show Working Example | Hide All


When you enter the correct password, the test returns true and the green section is executed. Anything else returns false and the red section is executed.


Elseif

Else gives you just one option if the if statement test returns false. Elseif will do another test. If it returns true, it's block of code is executed and it exits the if ststement. If false, it moves down to the next elseif or else. You can string along any number of elseif's. The else has to go on the end because it is executed if every other test is false and it is optional. Elseif can be written as one word or two. Basic syntax:

if ( test1 )
{ code executed if test1 is true }
elseif ( test2 )
{ code executed if test2 is true }
elseif ( test3 )
{ code executed if test3 is true }
else
{ code executed if no test returned true }


For an example, let's revisit the password script but make it for four people.:

Show Code | Show Working Example | Hide All


< ^ >


Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>