Session 3.2 – PHP Variables and Data Types

Module 3: PHP Basics | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Declare and use variables in PHP
  • Understand PHP variable naming conventions and rules
  • Identify and work with different data types in PHP
  • Perform type conversion and type checking
  • Understand PHP's type juggling system
  • Define and use constants in PHP

PHP Variables

What is a Variable?

A variable is a container that stores data values. In PHP, variables are used to store information that can be referenced and manipulated throughout your program.

Variable Declaration

In PHP, variables:

  • Start with the dollar sign ($)
  • Don't require explicit type declaration (loosely typed)
  • Are created automatically when you first assign a value
<?phplt;?phplt;?php
    // Variable declaration and initialization
    $name = "John";
    $age = 25;
    $price = 19.99;
    $isStudent = true;

    // Outputting variables
    echo "Name: " . $name . "<br>";
    echo "Age: " . $age . "<br>";
    echo "Price: $" . $price . "<br>";
    echo "Is Student: " . $isStudent;
?>
Output:
Name: John
Age: 25
Price: $19.99
Is Student: 1

Variable Scope

PHP has three variable scopes:

Local Scope

Variables declared within a function. Only accessible inside that function.

Global Scope

Variables declared outside functions. Accessible everywhere except inside functions (unless using global keyword).

Static Scope

Variables that retain their value between function calls.

Variable Naming Rules

Rules for Variable Names
  1. Must start with a dollar sign ($)
  2. After the $, must start with a letter or underscore
  3. Cannot start with a number
  4. Can only contain alpha-numeric characters and underscores (A-z, 0-9, _)
  5. Are case-sensitive ($name and $Name are different)

Valid and Invalid Variable Names

Valid Variable Names
$name
$_name
$name123
$firstName
$first_name
$NAME
$name_1
Invalid Variable Names
$1name       // starts with number
$first-name  // contains hyphen
$first name  // contains space
$first+name  // contains +
name         // missing $

PHP Data Types

PHP supports the following data types:

Data Type Description Example
String Sequence of characters "Hello World"
Integer Whole numbers 42, -10, 0
Float/Double Decimal numbers 3.14, -0.5
Boolean True or False true, false
Array Collection of values [1, 2, 3]
Object Instance of a class new MyClass()
NULL No value null
Resource Special variable holding a reference to external resource Database connection

String Data Type

Creating Strings

Strings can be created using single quotes or double quotes:

<?phplt;?phplt;?php
    // Single quotes
    $str1 = 'Hello World';

    // Double quotes
    $str2 = "Hello World";

    // Difference: Variable interpolation
    $name = "John";
    echo 'Hello $name';  // Outputs: Hello $name
    echo "Hello $name";  // Outputs: Hello John
?>

String Concatenation

<?phplt;?phplt;?php
    $firstName = "John";
    $lastName = "Doe";

    // Using dot (.) operator
    $fullName = $firstName . " " . $lastName;
    echo $fullName;  // Outputs: John Doe

    // Concatenation assignment
    $greeting = "Hello";
    $greeting .= " World";
    echo $greeting;  // Outputs: Hello World
?>

String Functions

<?phplt;?phplt;?php
    $text = "Hello World";

    echo strlen($text);           // 11 (length)
    echo strtoupper($text);       // HELLO WORLD
    echo strtolower($text);       // hello world
    echo str_replace("World", "PHP", $text);  // Hello PHP
    echo substr($text, 0, 5);     // Hello
?>

Numeric Data Types

Integer

Whole numbers without decimal point:

<?phplt;?phplt;?php
    $x = 5985;        // positive integer
    $y = -345;        // negative integer
    $z = 0x8C;        // hexadecimal (140 in decimal)
    $b = 0123;        // octal (83 in decimal)

    // Check if variable is integer
    var_dump(is_int($x));  // bool(true)
?>

Float/Double

Numbers with decimal point or in exponential form:

<?phplt;?phplt;?php
    $x = 10.365;      // decimal
    $y = 2.4e3;       // exponential (2400)
    $z = 8E-5;        // exponential (0.00008)

    // Check if variable is float
    var_dump(is_float($x));  // bool(true)
?>

Arithmetic Operations

<?phplt;?phplt;?php
    $a = 10;
    $b = 3;

    echo $a + $b;   // 13 (Addition)
    echo $a - $b;   // 7  (Subtraction)
    echo $a * $b;   // 30 (Multiplication)
    echo $a / $b;   // 3.333... (Division)
    echo $a % $b;   // 1  (Modulus)
    echo $a ** $b;  // 1000 (Exponentiation)
?>

Boolean Data Type

Boolean represents two possible states: TRUE or FALSE (case-insensitive):

<?phplt;?phplt;?php
    $isLoggedIn = true;
    $hasError = false;

    if ($isLoggedIn) {
        echo "Welcome back!";
    }

    // Comparison returns boolean
    $x = 10;
    $y = 20;
    var_dump($x > $y);   // bool(false)
    var_dump($x < $y);   // bool(true)
    var_dump($x == 10);  // bool(true)
?>
Falsy Values in PHP

The following values are considered FALSE when converted to boolean:

  • The boolean false itself
  • The integer 0 (zero)
  • The float 0.0 (zero)
  • The empty string "" and the string "0"
  • An array with zero elements
  • The special type NULL

Special Data Types

NULL Type

NULL represents a variable with no value:

<?phplt;?phplt;?php
    $x = null;
    var_dump($x);  // NULL

    // Check if variable is null
    if (is_null($x)) {
        echo "Variable is null";
    }

    // Unset variable becomes null
    $y = "Hello";
    unset($y);
    var_dump($y);  // NULL (with notice)
?>

Array Type

Arrays store multiple values in a single variable (covered in detail in Session 3.4):

<?phplt;?phplt;?php
    // Indexed array
    $colors = array("Red", "Green", "Blue");
    // Or using short syntax
    $fruits = ["Apple", "Banana", "Orange"];

    echo $colors[0];  // Red
    echo $fruits[1];  // Banana
?>

Type Juggling and Type Casting

PHP is a loosely typed language - it automatically converts types as needed (type juggling):

Automatic Type Conversion

<?phplt;?phplt;?php
    $x = "10";     // string
    $y = 5;         // integer
    $z = $x + $y;   // PHP converts "10" to 10, result is 15

    echo $z;      // 15 (integer)
?>

Explicit Type Casting

You can explicitly convert one data type to another:

<?phplt;?phplt;?php
    $x = "123";

    // Cast to integer
    $int = (int)$x;
    $int = (integer)$x;

    // Cast to float
    $float = (float)$x;
    $float = (double)$x;

    // Cast to string
    $str = (string)$int;

    // Cast to boolean
    $bool = (bool)$x;
    $bool = (boolean)$x;

    // Cast to array
    $arr = (array)$x;
?>

Type Checking Functions

<?phplt;?phplt;?php
    $var = 123;

    var_dump(is_int($var));      // bool(true)
    var_dump(is_float($var));    // bool(false)
    var_dump(is_string($var));   // bool(false)
    var_dump(is_bool($var));     // bool(false)
    var_dump(is_array($var));    // bool(false)
    var_dump(is_null($var));     // bool(false)
    var_dump(is_numeric($var));  // bool(true)

    // Get variable type
    echo gettype($var);        // integer
?>

PHP Constants

What are Constants?

Constants are like variables but their values cannot be changed once set. Constants are automatically global across the entire script.

Defining Constants

<?phplt;?phplt;?php
    // Using define() function
    define("SITE_NAME", "My Website");
    define("MAX_USERS", 100);
    define("PI", 3.14159);

    echo SITE_NAME;  // My Website
    echo MAX_USERS;  // 100

    // Using const keyword (PHP 5.3+)
    const DB_HOST = "localhost";
    const DB_NAME = "mydb";

    echo DB_HOST;  // localhost
?>
Constants vs Variables
  • Constants don't start with a dollar sign ($)
  • Constants are automatically global
  • Constants cannot be changed or undefined once set
  • By convention, constant names are usually uppercase

Magic Constants

PHP provides several predefined constants that change based on where they are used:

<?phplt;?phplt;?php
    echo __LINE__;      // Current line number
    echo __FILE__;      // Full path of the file
    echo __DIR__;       // Directory of the file
    echo __FUNCTION__;  // Function name
    echo __CLASS__;     // Class name
?>

Session Summary

Key Points
  • Variables in PHP start with $ and don't require explicit type declaration
  • Variable names are case-sensitive and must follow specific naming rules
  • PHP supports 8 main data types: String, Integer, Float, Boolean, Array, Object, NULL, and Resource
  • Strings can use single or double quotes; double quotes allow variable interpolation
  • PHP is loosely typed and performs automatic type conversion (type juggling)
  • Type can be explicitly cast using cast operators like (int), (string), etc.
  • Constants are defined using define() or const keyword
  • Constants are immutable and automatically global
  • Use var_dump() and type-checking functions to inspect variable types
Next Session Preview

In the next session, we will explore PHP Control Structures and Loops, learning how to make decisions and repeat operations in your PHP code.