SITERAW

PHP and Conditions

This chapter is super important. Seriously. You're going to be using conditions all the time. I probably should have called this chapter "Conditional Structures," but I decided to go with something simpler. Hope you don't mind 😉

So, what's the point of using conditions?

Well, sometimes you want your site to behave differently depending on certain data.

Say it's morning — you might want to greet your visitor with a friendly "Good morning!" But if it's evening, "Good evening" would be more appropriate.

This is where conditions come into play. They let PHP take different actions depending on the situation. In our case: If it's morning, display "Good morning." Else if it's evening, display "Good evening."

You'll see — conditions are absolutely essential if you want your site to be dynamic. That means showing different content based on things like who the visitor is, the time of day, the date, etc.

That's why this chapter is such a big deal!

The Basic Structure: If... Else

We call it a "structure" because it has a specific shape. The one I'm about to show you is the go-to way to write conditions in PHP.

Good news: there aren't fifty different ways to do it. Phew 😅

To get comfy with If... Else, we'll follow this plan:

  • Important Symbols: First, let's learn the symbols used for comparisons. You'll definitely need these.
  • The If... Else Structure: This is the meat of it. You'll see how a condition works, and yeah... you really need to get this part.
  • Multiple Conditions: We'll spice things up by using more than one condition at a time.
  • The Case of Booleans: We'll check out a cool trick when working with true/false values. (Not sure what a boolean is? You might wanna revisit the variables chapter.)
  • Bonus Tip: Because there's always a little bonus for those who make it to the end! 😄

Important Symbols to Know

Before we dive in, here's a quick cheat sheet of symbols we'll be using. Try to memorize them — they'll be your best buddies!

SymbolMeaning
==Is equal to
>Is greater than
<Is less than
>=Is greater or equal to
<=Is less or equal to
!=Is not equal to

Notice that == (double equals) is not the same as = (single equals). The single one assigns a value (like we saw with variables), while the double one checks if two things are equal.

Remember: inside conditions, you always use == to test equality.

The If... Else Structure

Here's how we write a condition in PHP:

  • We start with the keyword if.
  • Right after that, we put the condition in parentheses.
  • Then, just like with functions, we open curly braces {} and put inside whatever code should run if the condition is true.

Let's see it in action — nothing beats a good example:

<?php
if ($age <= 12)
{
    echo "Hey kid!";
}
?>

Here, we're telling PHP: If the $age is 12 or less, display "Hey kid!"

You'll notice that most of the time, we use variables in our conditions.

In this example, we're checking the $age variable. There are only two possible outcomes:

  • If the condition is true (i.e. age ≤ 12), the message is displayed.
  • Otherwise, PHP skips the code inside the curly braces. Nothing happens.

Let's improve this example and add something for older visitors:

<?php
$age = 8;

if ($age <= 12) // IF age is 12 or less { echo "Hey kid! Welcome to SiteRaw!<br />"; $allowed_in = "Yes"; } else // OTHERWISE { echo "Sorry, this site is for kids only. You're too old to enter. Goodbye!<br />"; $allowed_in = "No"; }

echo "Do you have access? The answer is: $allowed_in"; ?>

Go ahead and try it!

Here's how it works: we put multiple lines of code inside the curly braces — totally allowed. We also added the keyword else, which means "otherwise."

In plain English: If age ≤ 12, do this. Else, do that.

Test this out by changing the $age value at the top and see how the output changes. It's kinda fun!

You can put anything you want between the braces. In our case, we displayed a message and set the $allowed_in variable, which we can use later:

<?php
if ($allowed_in == "Yes") // IF we're allowed in
{
    // actions to run if access is granted
}
elseif ($allowed_in == "No") // ELSE IF we're not allowed in
{
    // actions to run if access is denied
}
else // ELSE (we don't know if it's Yes or No, so we can't decide)
{
    echo "Uhh... I don't know your age. Mind telling me again?";
}
?>

Whoa — it's getting a bit more complex, isn't it? 😅

The main new thing here is the elseif keyword, which means "else if." PHP goes through it step-by-step:

  • If $allowed_in is "Yes", do this...
  • Else if it's "No", do that...
  • Else, ask again because we don't know what's going on!

By the way, variables don't have a value when you first create them — they're NULL, which basically means "nothing."

If you want to check if a variable is empty, just write:

if ($variable == NULL)

Multiple Conditions and Elseif

You might be thinking: "Oh great, what crazy twist is he throwing at us now?" 😆

Well, things can always get a bit more complicated — you're probably used to that by now.

I couldn't not show you multiple conditions, because they're actually really useful. Hang in there, we're almost done!

Let's say we want to check several things at once. For that, we need a few new keywords. Here are the big ones:

KeywordMeaningSymbol Equivalent
ANDAnd&&
OROr||

For the OR symbol, you need to type two vertical bars (||). Keyboards change depending on your country, but the vertical bars are pretty easy to find... if all else fails, you can look up an ASCII character table (or just use ALT+124).

The first column shows the English keyword, and the third column shows its symbol version. Both work just fine, but I recommend using the keywords — it's easier to read 😉

You can use these to write multiple conditions inside your if parentheses. Here's an example:

<?php
if ($age <= 12 AND $gender == "boy")
{
    echo "Welcome to Calvin's G.R.O.S.S. website!";
}
elseif ($age <= 12 AND $gender == "girl")
{
    echo "This isn't a site for girls. Go play with Suzie!";
}
?>

It's simple and makes perfect sense: if the visitor is a boy and 12 or younger, they get into the site. If it's a girl aged 12 or under... well, we gently turn her away. (Please don't accuse me of sexism — it's just an example 😅)

One last example with OR before we wrap this up:

<?php
if ($gender == "girl" OR $gender == "boy")
{
    echo "Hello!";
}
else
{
    echo "Uhh... if you're neither a boy nor a girl, what are you exactly?";
}
?>

The Case of Booleans

If you think back to the $allowed_in example, don't you think it'd make more sense to use a boolean here?

We talked about booleans in the variables chapter. Remember?

Booleans are those special values that are either true or false. And they're perfect for use in conditions! Here's how you'd test a boolean:

<?php
if ($allowed_in == true)
{
    echo "Welcome, little noob! :o)";
}
elseif ($allowed_in == false)
{
    echo "You're not allowed in!";
}
?>

Nothing too wild here. Notice how we didn't use quotes around true and false (just like I said in the variables chapter).

But here's the cool part: with booleans, you can shorten your condition. You don't need == true... PHP gets the idea:

<?php
if ($allowed_in)
{
    echo "Welcome, little noob! :o)";
}
else
{
    echo "You're not allowed in!";
}
?>

PHP understands that this means "if $allowed_in is true." The benefits?

  • It's faster to type
  • It's easier to read

When you read the first line out loud, it sounds like: "If access is allowed..." Makes sense, right?

But wait! What if you want to check if it's false using the short method?

Simple — you use the exclamation mark ! like this:

if (!$allowed_in)

That's just another way of saying "if not allowed." If you prefer writing if ($allowed_in == false), that works too! But personally, I find the shorthand easier to read 😉

Bonus Tip: Mixing PHP and HTML

Here's a neat trick when you're working with conditions:

These two blocks of code do exactly the same thing:

<?php
if ($variable == 45)
{
    echo "<strong>Congrats!</strong> You found the secret number!";
}
?>

Is the same as:

<?php
if ($variable == 45)
{
?>
<strong>Congrats!</strong> You found the secret number!

<?php } ?>

In the second version, we didn't use echo. Instead, we opened a PHP block, started the condition, then closed the PHP tag so we could write plain HTML inside.

Super handy when you've got a lot of HTML to write, or if you want to avoid messing around with escaped quotes inside echo statements.

Just remember to close the curly brace afterward — inside a PHP block, of course.

And that's it! Nothing too scary, right?

You'll be using conditions a lot in future examples. As long as you follow the If... Else pattern we covered, you'll be fine. We'll get more practice soon, and you'll see for yourself how vital conditions are in PHP!

The Switch Alternative

In theory, the if... elseif... else structure I just showed you is perfectly capable of handling any condition you throw at it.

Then why are you trying to complicate our lives with yet another thing?!

Good question. Let me show you the usefulness of switch with a slightly bloated example using the if and elseif statements you just learned. Imagine we had quizes after all our courses (I once considered the idea, but while they have merit, they are also annoying for the user who just wants to speedrun the tutorial):

<?php
if ($score == 0) {
    echo "You're a total Noob!!! You've come to the right place to learn, though.";
}
elseif ($score == 5) {
    echo "You did really poorly.";
}
elseif ($score == 10) {
    echo "Not great.";
}
elseif ($score == 50) {
    echo "Barely average... just scraping by.";
}
elseif ($score == 75) {
    echo "Pretty decent.";
}
elseif ($score == 90) {
    echo "You're doing really well!";
}
elseif ($score == 100) {
    echo "Excellent work, perfect score!";
}
else {
    echo "Sorry, I don't have a message for that grade.";
}
?>

As you can see, it's bulky, repetitive, and not exactly elegant. In situations like this, there's a more flexible structure you can use: the magical switch.

Here's the same example using a switch (same outcome, way cleaner code):

<?php
$score = 10;

switch ($score) { // this tells PHP which variable we're working with

case 0: echo "You're a total Noob!!! You've come to the right place to learn, though."; break;

case 5: echo "You did really poorly."; break;

case 10: echo "Not great."; break;

case 50: echo "Barely average... just scraping by."; break;

case 75: echo "Pretty decent."; break;

case 90: echo "You're doing really well!"; break;

case 100: echo "Excellent work, perfect score!"; break;

default: echo "Sorry, I don't have a message for that grade."; } ?>

Go ahead, test this code!

Try changing the grade (in the first line) and see how PHP responds! And if you want to tweak the code a little (you'll notice it's not totally perfect), feel free — it's great practice!

A few things to notice:

  • First, there are way fewer curly braces (just one set around the switch).
  • The keyword case just means... well, "case." You start off by telling PHP which variable you want to evaluate ($score in this "case"). You're basically saying: "Hey PHP, let's check the value of $score."
  • Then for each possible value, you add a case:
  • case 0, case 10, and so on.
  • It's like saying: "If the value is 0...", "If the value is 10..."

Benefits: You no longer need to write those double equals (==)!

Downsides: It only works for equality checks. You can't use it with <, >, <=, >=, !=, etc. In short, switch is strictly for equality testing.

That default keyword at the end? It's like the else in an if block. It's the fallback message that appears if none of the case values match.

Now, one very important thing to keep in mind.

Let's say $score = 50. PHP will read your code like this:

case 0? Nope, skip.
case 5? Nope, skip.
case 10? Nope, skip.
case 50? Yes! Execute the code!

BUT, unlike elseif, PHP won't stop there — it will keep going, running the code for the next cases too: case 75, case 90, etc. 😱

To prevent this from happening, you need to use the break; statement.

break tells PHP: "Alright, I'm done here. Get me outta this switch."

As soon as PHP hits break, it exits the switch block and doesn't read the remaining cases.

In practice, you almost always use break — otherwise, PHP will keep executing all the following code, even if it doesn't match the value.

Try removing the break statements from the example above, and you'll quickly understand why they're absolutely essential!

When should you use If vs. Switch?

It's mostly about readability and clarity.

For short and simple conditions, stick with if. But when you're checking a bunch of specific values, switch is much clearer and cleaner! 😊

Ternary Operators, conditions on a diet

There's another way to write conditions — way less common — but I'm showing it to you anyway because you might run into it one day.

It's called the ternary operator.

A ternary is like a super-condensed condition that does two things on one single line:

  • It checks a condition.
  • It assigns a value based on whether that condition is true or false.

Here's a basic if... else that sets a Boolean variable $adult to true or false depending on the visitor's age:

<?php
$age = 21;

if ($age >= 18) { $adult = true; } else { $adult = false; } ?>

Now here's the exact same logic using a ternary — on just one line:

<?php
$age = 21;

$adult = ($age >= 18) ? true : false; ?>

See that? Our entire previous block got squished into one neat line!

Here's what's happening:

  • The condition being tested is $age >= 18.
  • If that's true, the value after the question mark (true) gets assigned to $adult.
  • If it's false, PHP assigns the value after the colon (false) instead.

It's a bit brain-bending at first... but it works! 😄

If you decide not to use ternaries in your own web pages, I totally understand. Let's be honest — they're kinda hard to read because they're so compact.

But at least now you know how to recognize and understand them if you ever stumble across one in someone else's code!

How to Build a Website in HTML and CSS

Enjoyed this PHP & MySQL course?

If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.

More information