Difference between revisions of "PHP106"

From mi-linux
Jump to navigationJump to search
Line 150: Line 150:
 
   echo "Think about it !";
 
   echo "Think about it !";
 
  }
 
  }
?&gt;</nowiki></pre>
+
?&gt;</nowiki></pre>
 
If the above were to be evaluated, you would not walk to work since you need both conditions to be true. In this example it is a weekday, but the weather is not good. The &amp;&amp; symbol means 'AND' so the 'If' statement can be paraphrased as "If it is a weekday, and the weather is good, then walk to work, else think about it."
 
If the above were to be evaluated, you would not walk to work since you need both conditions to be true. In this example it is a weekday, but the weather is not good. The &amp;&amp; symbol means 'AND' so the 'If' statement can be paraphrased as "If it is a weekday, and the weather is good, then walk to work, else think about it."
  
Line 171: Line 171:
 
   echo "Think about it !";
 
   echo "Think about it !";
 
  }
 
  }
?&gt;</nowiki></pre>
+
?&gt;</nowiki></pre>
 
In the code above the symbol '||' represents ‘OR’
 
In the code above the symbol '||' represents ‘OR’
  

Revision as of 13:16, 29 June 2016

Main Page >> Web Application Development >> Workbook >> Flow Control - Selection

Flow Control

Decisions, Decisions!

So far, we learnt to write some simple PHP code, the main feature of which is that every line of code is executed. At times you may wish code to be executed only if certain conditions apply. 'If' statements are used to compare two values and carry out different actions based on the results of the test. If statements take the form IF, THEN, ELSE. Basically the IF part checks for a condition. If it is true, the then statement is executed. If not, the else statement is executed. Sounds complicated? - It's not.

For example, if today is a weekday get up and go to University, else stay in bed. This can be generally represented by:

<? if ($today == "Monday") [1] { // Go to University [2] } else { // Stay in bed [3] } ?>
  • [1] The test which is evaluated
  • [2] The action to be carried out if the test evaluates as True
  • [3] The action to be carried out if the test evaluates as False

Note: - you may require that several lines are executed, rather than a single statement, and it would be written like the following:

<? if ($num > 10) { statement; statement; statement; } else { statement; statement; } ?>

Note: - the braces delineate the two blocks of code, the use of brackets in the IF statement, and the semi-colons to mark the end of each of the five statements.

if

One of the most common uses of an IF statement is to compare a variable to another piece of text, a number, or another variable. For example:

<?
   if ($username == "webmaster")
   ...
   ...
   ...
 ?>

...which would compare the contents of the variable $username to see if the value (hence the two equals signs) is the same as "webmaster". If it is the 'then' section of code will be executed. Exactly equal to means that if $username contained "Webmaster" or "WEBMASTER" the test would evaluate as false, as the case of the string does not match.

<?php
   if ($username == "webmaster") {
      echo "Please enter your password below";
   }
 ?>

...this will only display this text if the username is webmaster. If not, nothing will be displayed. You can actually leave an IF statement like this, as there is no actual requirement to have an ELSE part. This is especially useful if you are using multiple IF statements.

else

Adding The ELSE statement is as easy as the THEN statement. Just add some extra code:

<?php
   if ($username == "webmaster") {
      echo "Please enter your password below";
   } else {
     echo "We are sorry but you are not a recognised user";
   }
 ?>

Of course, you are not limited to just one line of code. You can add any PHP commands in between the braces. You can even include other IF statements (nested statements).

Other Comparisons

There are other ways you can use your IF statement to compare values. Firstly, you can compare two different variables to see if their values match e.g.

if ($enteredpass == $password)

You can also use the standard comparison symbols to check to see if one variable is greater than or less than another:

if ($age < 13)

Or :

if ($date > $finished)

You can also check for multiple tests in one IF statement. For instance, if you have a form and you want to check if any of the fields were left blank you could use:

<?php
   if ($name == "" || $email == "" || $password == "") {
      echo "Please fill in all the fields";
   }
 ?>

elseif

If a number of consecutive IF statements are required, these may be linked using the ELSEIF statement.

<?php
   $num = 15;
   if ($num < 5) {
     echo "Number is very small";
   } elseif ($num < 10 ) {
     echo "Number is small";
   } elseif ($num < 20) {
     echo "Number is big";
   } elseif ($num < 30) {
     echo "Number is very big";
   }
 ?>

A programmer has the choice of using either format, however if these become unduly lengthy then they are best replaced with the Switch statement.

switch

The 'switch' statement is a more compact, readable and efficient form of dealing with multiple 'If' conditions. It is much easier to read, and de-bug. It is ideal for when an option has to be chosen from a list of choices. The following code shows how the user has made a choice, which has been stored in the variable $menu, and the code then selects what form of action is necessary - according to the user's choice. In this case it merely repeats back the user's choice.

<?php
   $menu = 3;
   switch ($menu) {
     case 1:
       echo "You chose number one.";
       break;
     case 2:
       echo "You picked number two.";
       break;
     case 3:
       echo "You picked number three.";
       break;
     case 4:
       echo "You picked number four.";
       break;
     default:
       echo "You picked another option";
   }
 ?>

Note: - the braces which show the start and finish of this construct, the use of the 'break' statement (this ensures that only one of the options is executed, by finding a matching option and breaking out of the 'switch' construct at that point, the use of semi-colons and the fact that more than one statement can be executed.

Conditional Expressions

We have used the double equals sign to see if two expressions are the same. There are other conditional comparisons which can be used, particularly with the 'If' statement.

We can use the inequality operator to test if a variable is not equal to an expression. Consider this code:

<?php
 $num = 0;
 if ($num != 1) {
   echo "Does not equal one 1";
 }
?>

The expression evaluates to be True (1 does not equal 0), and therefore the 'echo' statement is executed.

It may also be necessary to evaluate whether or not two conditions both hold true, or if one of two conditions hold true. If we wish to evaluate that both conditions are true we use 'AND', if only one or the other needs to be true we use 'OR'. This is best shown in the following examples:

  • Condition A - Is it a Weekday ?
  • Condition B - Is it good weather ?
  • Result - If A and B are both True, walk to work
  • Result - If either A or B are not True, then think about it

This could be represented by the following code, which uses two Boolean variables '$weekday' and '$good_weather'

<?php
 // Note that Booleans hold the value true or false,
 // not the strings 'true' or 'false'
 $weekday = true;
 $good_weather = false;
 if (($weekday == true) && ($good_weather == true)) {
   echo "It is a nice day, why not walk to work ?";
 } else {
   echo "Think about it !";
 }
?>

If the above were to be evaluated, you would not walk to work since you need both conditions to be true. In this example it is a weekday, but the weather is not good. The && symbol means 'AND' so the 'If' statement can be paraphrased as "If it is a weekday, and the weather is good, then walk to work, else think about it."

The other common conditional operator is 'OR'. This is used when only one condition or the other needs to be true, for the statement to be executed. Using the example above leads to some interesting results, as is shown:

  • Condition A - Is it a Weekday ?
  • Condition B - Is it good weather ?
  • Result - If A or B are True, walk to work
  • Result - If both A and B are not True, then think about it

The code for this is as follows:

<?php
 // Note that Booleans hold the value true or false,
 // not the strings 'true' or 'false'
 $weekday = true;
 $good_weather = false;
 if (($weekday == true) || ($good_weather == true)) {
   echo "It is a nice day, why not walk to work ?";
 } else {
   echo "Think about it !";
 }
?>

In the code above the symbol '||' represents ‘OR’

Ready to move on?

PHP107 - Flow Control - Iteration