Hello World Master

Tutorials, articles and quizzes on Software Development

PHP > Articles

If statements in PHP

Associated Courses

This article is associated with the following course:

Introduction to PHP

If statements allow us to call lines of code depending on whether or not certain conditions are met for a statement.

In most programming languages, we evaluate a variable against another value or variable to determine whether or not its true.

So lets say you own a cat. If we own a cat then we should feed that cat. In PHP code we can express that we want to feed the cat like this

<?php
  $hasCat = true;
  if($hasCat == true) {
    echo "Lets feed the cat";
  }
?>

Else statements

What if we don’t have a cat, then we can add an else statement to echo a different string

<?php
  $hasCat = true;
  $hasDog = false;
  if($hasCat == true) {
    echo "Lets feed the cat";
  } else {
    echo "We don't have a cat to feed";
  }
?>

Else if statements

We might not have a cat, but we do have a dog, lets add an else if statement to echo out a string that tells us to feed the dog instead.

<?php
  $hasCat = true;
  $hasDog = true;
  if($hasCat == true) {
    echo "Lets feed the cat";
  } else if($hasDog == true) {
    echo "We don't have a cat, but lets feed the dog";
  } else {
    echo "We don't have a cat to feed";
  }
?>

Multiple conditions for one if statement

What if we have a cat and a dog, then we could have our if statement check to see whether or not we have both a cat and a dog.

We need to add two ampersand (&) signs do add another conditional to our if statement. We also need to change our if statement checking if the variable hasCat is true to be an else if statement, otherwise, we’ll end up printing out its value as well.

<?php
  $hasCat = true;
  $hasDog = true;
  if($hasCat == true && $hasDog == true) {
    echo "Lets feed both the cat and the dog";
  } else if($hasCat == true) {
    echo "Lets feed the cat";
  } else if($hasDog == true) {
    echo "We don't have a cat, but lets feed the dog";
  } else {
    echo "We don't have a cat to feed";
  }
?>

Remember, when our if statement condition returns false, we then move on to check the other if statements, so here if we don’t have a dog or a cat, we can just check to see if we have just a dog or just a cat.