👨🏼‍💻 Part 3: If and else statements

So what makes PHP, or any programming language dynamic? The possibility of using if and else statements.
You can handle data based on different conditions.
Basic examples:

  • on some site, say Facebook, if site viewer is logged in, show user interface, otherwise show login form
  • in Patchstack, check if user is on a Developer plan or Community plan. If user_plan == 6, show reports page, otherwise don’t show reports page
  • on some random website, if user has clicked submit button on a form, send an email and show thank you message; otherwise show contact form
  • if website URL has language parameter “/en”, load website in English language, else if “/fi”, load Finnish language, else show Estonian language

If-statement requires a statement if(), opening bracket {, and closing bracket }.
Inside the ( ), you’ll need to write the condition; and all the magic happens between the brackets.

So, a basic if-statement looks like this.

$myAge = 17; // let's declare, what's my age

if ( $myAge < 18 ) {
   echo "You are not allowed to buy cigarettes.";
}

You should see the message, until you change the value of $myAge to something higher than 18.

But what if we are over 18, and want to buy these cigarettes? Now let’s add an else-statement there as well.

$myAge = 19; // let's declare, what's my age

// for debugging purposes, it will print out the variable so we can test.
echo "Your age is: " . $myAge . "<br>";

if ( $myAge < 18 ) {
    echo "You are not allowed to buy cigarettes.";
}
else {
    echo "OK! I'm convinced you are allowed to buy your cigarettes.";
}

As you can see, the else-statement is pretty easy – you just add the “else {“, and all the magic again happens between the curly brackets. “}”.

Let’s play russian roulette with PHP

Let’s make a PHP russian roulette game, where on every page refresh, we see, if we were lucky or not.
First, let’s think of an algorithm… well, it’s fairly simple:
1. Generate a random number between 1 and 6
2. Check if that number equals for example 5
3. If the random number equals 5, show some bad luck message

$randomNumber = rand(1,6);

if( $randomNumber == 5 ) {
   echo "<span style='color: red;'>PHP won the game!</span>";
}
else {
   echo "<span style='color: green;'>You won the game!</span>";
}

You can also add a debugging line here, and echo the $randomNumber, to test your program.

Independent exercise

Write a program that would tell you what to do if it’s raining outside.

  1. Define in some variable, if it’s raining or not. So – name some variable and give it a value. For value, use some recognizable string, like “yes” or “no”
  2. Write an if-statement which checks wether it’s raining or not
  3. If it’s raining, say “Take an umbrella!”
  4. If it’s not raining, say “Screw your umbrella!”

Scroll to Top