PHP Conditionals for Beginners

What Are Conditionals?

PHP conditionals let your code make decisions. They help your program choose what to do based on whether something is true or false.

As a beginner, you will use conditionals to check values, compare variables, and control which code runs next.

The if Statement

The if statement runs a block of code only when a condition is true.

Example: if a user is logged in, show their dashboard.

  • Use if for a single condition
  • Use comparison operators like ==, ===, >, and <
  • Keep conditions simple when learning

The else Statement

The else statement gives you a fallback. If the if condition is false, the else block runs instead.

This is useful when your code needs two possible paths, such as showing “Access granted” or “Access denied.”

The elseif Statement

Use elseif when you want to check more than two possibilities.

  • if checks the first condition
  • elseif checks another condition if the first one fails
  • else handles everything left over

Common Comparison Operators

  • == means equal to
  • === means equal value and equal type
  • != means not equal to
  • > means greater than
  • < means less than

A Simple Example

$age = 20;
if ($age >= 18) {
  echo "You are an adult.";
} else {
  echo "You are under 18.";
}

In this example, PHP checks the value of $age. Because 20 is greater than or equal to 18, the first message runs.

Tips for Beginners

  • Start with simple true or false checks
  • Use clear variable names
  • Test different values to see how your code behaves
  • Practice reading conditions out loud

Final Thoughts

Conditionals are one of the most important parts of PHP. Once you understand if, else, and elseif, you can build smarter and more interactive programs.

Next, you can continue learning by exploring switch statements and loops.