Data Types & Variables

Learn about PHP variables, data types, math operations, and arrays.

Variables & Data Types

PHP is loosely typed - variables don't need type declarations. Learn how to work with different data types.

Variables

PHP
<?php
// String
$name = "PHP Learning";
echo $name;

// Integer
$version = 8.2;

// Float
$price = 19.99;

// Boolean
$isAwesome = true;

// NULL
$empty = null;

// Output
echo "Version: " . $version;  // Version: 8.2
?>
  • Variables start with $ followed by a letter or underscore
  • Variable names are case-sensitive ($name$Name)
  • PHP is loosely typed - same variable can hold different types
  • Use var_dump() to check variable type and value

Math Operations

PHP Math
<?php
$a = 10;
$b = 3;

// Basic operators
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/Remainder)
echo $a ** $b;   // 1000 (Power/Exponent)

// Increment/Decrement
$a++;            // 11
$a--;            // 10

// Built-in math functions
echo abs(-5);           // 5
echo round(3.7);        // 4
echo sqrt(16);          // 4
echo max(1, 5, 3);      // 5
echo min(1, 5, 3);      // 1
echo rand(1, 100);      // Random 1-100
?>

Indexed Arrays

PHP Arrays
<?php
// Array creation
$colors = array("Red", "Green", "Blue");
// or (modern syntax)
$colors = ["Red", "Green", "Blue"];

// Access elements (0-indexed)
echo $colors[0];        // Red
echo $colors[1];        // Green

// Add element
$colors[] = "Yellow";   // Appends to end
array_push($colors, "Purple");

// Array functions
count($colors);         // Number of elements
sort($colors);           // Sort ascending
rsort($colors);          // Sort descending
in_array("Red", $colors); // true/false

// Loop through array
foreach ($colors as $index => $color) {
    echo "$index: $color<br>";
}
?>

Associative Arrays

PHP Associative Array
<?php
// Key-Value pairs
$student = [
    "name" => "John",
    "age" => 25,
    "grade" => "A"
];

// Access by key
echo $student["name"];     // John
echo $student["age"];       // 25

// Add/Update
$student["email"] = "john@email.com";
$student["age"] = 26;

// Loop through
foreach ($student as $key => $value) {
    echo "$key: $value<br>";
}

// Useful functions
array_keys($student);       // Get all keys
array_values($student);     // Get all values
array_key_exists("name", $student);  // true
?>

Hands-on Exercises

Exercise 1: Create variables for your name, age, and city
Exercise 2: Calculate the area of a rectangle (width × height)
Exercise 3: Create an array of 5 favorite movies, then loop through and display them
Exercise 4: Create a student associative array with name, major, and GPA
Exercise 5: Use array functions to sort and search an array