Learn to Code via Tutorials on Repl.it

← Back to all posts
PHP Tutorial No. 3: Decisions
h
malvoliothegood (255)

#PHP Tutorial No. 3: Decisions

Here is a link to the Control Structures section of the PHP language reference. It contains additional information about what is covered on this page.

As mentioned in previous tutorials, PHP syntax is very similar to C and JavaScript. Decisions consist of: if, if/else, if/else if, and so on.
##if
The if construct consists of the word "if" followed by a set of curved brackets, which in turn is followed by a set of curly braces {}. If te expression inside the brackets evaluates to true then the code within the braces is evaluated.

Below is some sample code that illustrates how to use if.

$name = "Donald Trump";
if ($name == "Donald Trump") {
    echo "Hello Mr President";
}

$number = rand(0, 100); // rand returns an integer in the range 0 to 100 inclusive
if ($number > 10 && number < 20) {
    echo "The random number is $number, and it is greater than 10 and less than 20";
}

$number = rand(-100, 100); Previous section: Variables
if ($number < 0 && $number % 2 == 0) {
    echo "The random number is $number, and it negative and even";
}

Often if is combined with else. Below is some sample code that illustrates how to use them together.

$number = rand(0, 10);
$guess = rand(0, 10);
if ($guess == $number) {
    echo "$guess and $number are the same";
} else {
    echo "$guess and $number are different";
}

More complex logic can be represented by the use of combinations of ifs and elses.

$mark = rand(50, 100); // $mark is a random integer in the range 50 to 100 inclusive
$grade = "";
if ($mark > 100 || $mark < 0) {
    echo "You can not get a mark more than 100 or less than 0";
} else if ($mark >= 90) {
    $grade = "A";
} else if ($mark >= 85) {
    $grade = "B";
} else if ($mark >= 60) {
    $grade = "C";
} else if ($mark >= 50) {
    $grade = "D";
} else {
    $grade = "F";
}

echo "Your mark is $mark and your grade is $grade";

Mainly for tidiness a switch construct can be used in place of multiple if/else/ifs, like so:

$mark = rand(50, 100); // $mark is a random integer in the range 50 to 100 inclusive
$grade = "";
switch ($mark) {
   case ($mark > 100 || $mark < 0):
        echo "You can not get a mark more than 100 or less than 0";
        break; // break stops the rest of the cases from being evaluated
   case ($mark >= 90):
          $grade = "A";
          break;
   case ($mark >= 85):
          $grade = "B";
          break;
   case ($mark >= 60):
          $grade = "C";
          break;
   case ($mark >= 50):
          $grade = "D";
   default:
          $grade = "F";  // The default case will be used if no other cases match   
 }    

 echo "Your mark is $mark and your grade is $grade";

An example program that uses Switch

Previous section in the tutorial: Variables