ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

A Server Side Web Tutorial Series # 4 - PHP Conditional Statements

Updated on May 6, 2014

The if, if...else, and if..elseif Statements


PHP has a number of conditional statements which begin with the keyword if:

  • if statement - executes some statement or statements (referred to as a code block only if a specified condition is true
  • if...else statement - executes one code block if a specified statement is true and another code block if the condition happens to be false
  • if...elseif....else statement - selects one of several blocks of code to be executed

The format of the if statement is

if (the named condition which can evaluate to either true or false goes here) {

the statement or statements (the code block goes here if the condition is true

} // the code block is encapsulated in between the curly braces


The if...else statement has an alternative code block to execute if the condition is false. The outline of the if...else statement is:

if (the named condition which can evaluate to either true or false goes her) {

the statement or statements (the code block goes here if the condition is true

} else

{ the statement or statements (the code block goes here if the condition is false

} // Note : both code blocks are enclosed in curly braces

The if...else...if statement adds an if statement after the curly brace which ended to code block executed when the condition in the first if was false.

This if...elseif....elseif.... could be continued for as many conditions which might have to be check for, but as one can see this could get quite messy. Fortunately there is an alternative, the switch statement which will be covered in the next secion.

The simple snapshots which follow illustrate the if and if...else and if...elseif constructs.

Examples of if, if...else, if...elseif Conditional Statenebt Use

A simple if statement. The condition is met so the message is echoed to the screen.
A simple if statement. The condition is met so the message is echoed to the screen.
A simple if...elxe statement the if condition met so that is the message we see on the screen. Nothing is echoed from the else code block. The else code block is ignored.
A simple if...elxe statement the if condition met so that is the message we see on the screen. Nothing is echoed from the else code block. The else code block is ignored.
An example of an if...elseif conditional statement.
An example of an if...elseif conditional statement.

The switch Statement

The switch statement presents a cleaner and more understandable way of coding where there are more than two possibilities exist. Generally we have some variable which can take on a number of values. The switch statement compares the variable against each condition in turn until the variable when considered evaluates to true.

Consider the following example. There are seven days in the week and for each of the days we perform some task. (e.g. go to church on Sunday, mow the grass on Monday, buy groceries on Tuesday, etc.

In switch statement pseudo code the switch statement would look something like this:

indicate the day of the week with the variable:

$dayofweek

The switch statement would be invoked as follows: switch($day of week)

The actions for each of the day of the week are indicated by cases for example, For Sunday and Monday the cases would be coded as follows:

case "Sunday":

perform the "go to church" activity"

then we exit the switch statement with the keyword break


case "Monday":

perform the activity "mow the lawn"

and again we exit the switch statement with the keyword break

..........and continue on with cases

Now, not all days would necessarily have actions or the actions might be identical. For this, rather than iterating over each day of the week, we would specify a special case, the default case:

default:


some default action or no action could be indicated here.

The basic outline becomes

switch(condition to be tested)

case 1:actions break

case 2: actions break

....more cases here.....

default: actions

and the switch statement would end.

A switch statement in PHP is illustrated in the snapshot which follows.


An Example of the Use of the switch Statement

The cases of Sunday and Monday failed. There was a matchon Tuesday. So that message was echoed.
The cases of Sunday and Monday failed. There was a matchon Tuesday. So that message was echoed.

PHP Loops, Another Form of Conditional Statements

In PHP (as in other programming languages there are times we want to perform identical actions while some condition is true. Often we want to iterate in some block of code The following looping (conditional) statements are:

  • while - loops through a block of code as long as the specified condition is true
  • do...while - always perfrom some code block at least once and then determine whether it ought to be repeated as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

The following sections discuss each of these constructs in detail.

The while Statement

The syntax of the while statement is rather simple:

while(condition is true)

{

code block to execute while the condition is true

}

An example of the while statement in action follows in the snapshot.

A while Conditional Statement Example

The statement will be repeated until the condition become false.
The statement will be repeated until the condition become false.

The do...while Statement

The do.....while statement is distinguished in that the code block is executed before the keyword is encountered. Thus, the code block is always executed at least once and then however many times if the condition being checked remains true.


The outline of the do...while statement is:

do

{

code block to be executed

}

while(condition is true)

An example follows in the snapshot.


The do....while Statement

Irrespective that the value of $x exeeds the condition in the while statement, the code block is executed.
Irrespective that the value of $x exeeds the condition in the while statement, the code block is executed.

The for Statement

The for loop is executed a specific number of times:

The syntax of the for statement is as follows:

for(an initial counter value; test the counter; increment the counter){

execute the code block

}

The for loop has three parameters:

  • initial counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to true, the loop will continue. If false the loop ends.
  • increment counter: Increments the loop counter value

The snapshot illustrates the use of the for counter.

The for Statement

The for statement.. $xis initialized to 0. While $x is less than or equal to 6, the message is printed. The counter is incrented after the for statement is encountered.
The for statement.. $xis initialized to 0. While $x is less than or equal to 6, the message is printed. The counter is incrented after the for statement is encountered.

The foreach Loop

We have not discussed arrays as such in these tutorials, This section is placed here to give the reader the complete set of conditional statements in PHP in one place. The foreach loop with be reviewed in out tutorial on arrays.

The foreach loop works only on arrays. It is used to loop through each key/value pair in an array

The syntax of the foreach loop is:

foreach($array as $value){

execute the code block

}

A simple example is in the snapshot which follows. The $array refers to the array by name. The $value is a way of referring to a key/value pair in the code block.

The foreach Statement

The foreach statement. This looping statement works only with arrays. We will deal with arrays in our next tutorial.
The foreach statement. This looping statement works only with arrays. We will deal with arrays in our next tutorial.

Was This Enough Information on Conditional and Looping Statements?

Cast your vote for Was this enough information to help your coding of PHP?

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)