Skip to content

Lesson 1: Variables and Data Types

Objective:

The primary objective of this lesson is to introduce learners to the fundamental concepts of variables and data types in PHP. By the end of this lesson, participants should be able to:

  • Understand the concept of variables and their role in storing data.
  • Declare variables in PHP and follow the naming conventions.
  • Differentiate between common data types such as integers, strings, floats, and booleans.
  • Assign values to variables and check their data types using appropriate functions.

1.1 Declaring Variables

1.1.1 Introduction to Variables

In PHP, a variable is a symbolic name for a value. This section will cover the basics of declaring variables, naming conventions, and assigning values.

<?php
    $name = "John";
    $age = 25;
    $isStudent = true;
?>

1.1.2 Variable Naming Rules

Explore the rules for naming variables, including case-sensitivity, starting with a letter or underscore, and avoiding reserved words.

1.1.3 Variable Assignment

Learn how to assign values to variables using the assignment operator =.

1.2 Understanding Data Types

1.2.1 Integer

Understand the concept of integers as whole numbers without decimal points.

<?php
    $quantity = 10;
    $population = 5000000;
?>

1.2.2 String

Explore strings as sequences of characters enclosed in single or double quotes.

<?php
    $name = "Alice";
    $message = 'Hello, PHP!';
?>

1.2.3 Float

Learn about floats, representing numbers with decimal points.

<?php
    $price = 19.99;
    $pi = 3.14;
?>

1.2.4 Boolean

Introduce booleans as variables that represent true or false values.

<?php
    $isStudent = true;
    $hasCar = false;
?>

1.2.5 Checking Data Types

Use the gettype() function to check the data type of a variable.

<?php
    $age = 25;
    echo gettype($age);  // Outputs: integer
?>

1.3 Practice Exercise

Apply the knowledge gained by writing a PHP script that declares variables for personal information, prints them along with their data types, and reinforces understanding.

<?php
    // Declare variables
    $myName = "YourName";
    $myAge = 20;
    $myHeight = 5.9;
    $isStudent = true;

    // Print out variables and their data types
    echo "Name: $myName, Type: " . gettype($myName) . "<br>";
    echo "Age: $myAge, Type: " . gettype($myAge) . "<br>";
    echo "Height: $myHeight, Type: " . gettype($myHeight) . "<br>";
    echo "Student: $isStudent, Type: " . gettype($isStudent) . "<br>";
?>