PHP / PHP Basics

Control Structures: If, Else, and Switch

In this tutorial, we’ll explore the 'if', 'else', and 'switch' control structures in PHP. We will learn how to use these structures to control the flow of a PHP script based on di…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Introduces the fundamentals of PHP, including syntax, variables, and basic control structures.

Control Structures: If, Else, and Switch in PHP

1. Introduction

Goal of the Tutorial

This tutorial aims to provide an understanding of the 'if', 'else', and 'switch' control structures in PHP. These are fundamental components for controlling the flow of a PHP script based on different conditions.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand and use 'if', 'else', and 'switch' control structures in PHP.
- Write PHP scripts that react differently to different conditions.

Prerequisites

A basic understanding of PHP and its syntax is required. Familiarity with the concepts of variables and data types in PHP will be beneficial.

2. Step-by-Step Guide

'If' Control Structure

The 'if' control structure is used to execute a block of code if a specified condition is true.

if (condition) {
  // code to be executed if the condition is true
}

'Else' Control Structure

The 'else' control structure is used to execute a block of code if the same condition is false.

if (condition) {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

'Elseif' Control Structure

The 'elseif' control structure is a combination of 'if' and 'else'. It can be used to add more conditions.

if (condition1) {
  // code to be executed if condition1 is true
} elseif (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else {
  // code to be executed if both condition1 and condition2 are false
}

'Switch' Control Structure

The 'switch' control structure is used to select one of many blocks of code to be executed.

switch (n) {
  case label1:
    // code to be executed if n=label1
    break;
  case label2:
    // code to be executed if n=label2
    break;
  default:
    // code to be executed if n is different from both label1 and label2
}

3. Code Examples

'If' Control Structure Example

$age = 20;
if ($age >= 18) {
  echo "You are eligible to vote.";
}

In this example, if the age is greater than or equal to 18, the message "You are eligible to vote." will be printed.

'If-Else' Control Structure Example

$age = 15;
if ($age >= 18) {
  echo "You are eligible to vote.";
} else {
  echo "You are not eligible to vote.";
}

In this example, if the age is less than 18, the message "You are not eligible to vote." will be printed.

'If-Elseif-Else' Control Structure Example

$score = 85;
if ($score > 90) {
  echo "Excellent score!";
} elseif ($score > 70) {
  echo "Good score!";
} else {
  echo "Try harder!";
}

In this example, if the score is greater than 70 but less than or equal to 90, the message "Good score!" will be printed.

'Switch' Control Structure Example

$day = "Mon";
switch ($day) {
  case "Mon":
    echo "Today is Monday.";
    break;
  case "Tue":
    echo "Today is Tuesday.";
    break;
  default:
    echo "Invalid day.";
}

In this example, if $day is "Mon", the message "Today is Monday." will be printed.

4. Summary

In this tutorial, we covered the 'if', 'else', and 'switch' control structures in PHP, how to use them, and their syntax. We also looked at practical examples of each control structure.

Continue your PHP learning journey by exploring more advanced control structures, such as loops and functions.

5. Practice Exercises

  1. Write a PHP script that determines whether a number is positive, negative, or zero using 'if-else' control structure.
  2. Write a PHP script that determines the grade of a student based on a score using 'if-elseif-else' control structure.
  3. Write a PHP script that prints the name of a day based on its numeric representation (1 for Monday, 2 for Tuesday, and so on) using 'switch' control structure.

Tips for further practice

  • Create more complex conditions using logical operators.
  • Use nested 'if' and 'switch' statements.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Image Converter

Convert between different image formats.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help