PHP Fundamentals

Variables & Data Types

13 min Lesson 3 of 45

Variables & Data Types

Variables are containers for storing data values. In this lesson, we'll explore how to create and use variables in PHP, and understand the different types of data PHP can handle.

What is a Variable?

A variable is a symbolic name for a value that can change during program execution. Think of it as a labeled box where you can store different types of information.

<?php $name = "John"; // Variable storing a string $age = 25; // Variable storing a number $isStudent = true; // Variable storing a boolean ?>

Variable Naming Rules

PHP has specific rules for naming variables:

Rules: 1. Must start with a dollar sign ($) 2. Must start with a letter or underscore after $ 3. Can contain letters, numbers, and underscores 4. Cannot contain spaces 5. Are case-sensitive ($name ≠ $Name) ✓ Valid Variable Names: $name $_name $name123 $firstName $first_name $USER_ROLE ❌ Invalid Variable Names: $123name // Cannot start with number $first-name // Cannot contain hyphens $first name // Cannot contain spaces $first.name // Cannot contain dots
Best Practice: Use descriptive names (camelCase or snake_case) that clearly indicate what the variable stores. Prefer $firstName or $first_name over $fn.

Declaring and Assigning Variables

PHP is loosely typed - you don't need to declare the variable type. PHP automatically determines the type based on the value.

<?php // Declaration and assignment in one step $username = "JohnDoe"; // Multiple assignments $x = $y = $z = 10; // Changing variable value $count = 5; $count = 10; // Now $count is 10 // Variables can change type $value = 100; // Integer $value = "text"; // Now string (not recommended) ?>
Important: While PHP allows changing variable types, it's better to maintain consistent types for clarity and avoid bugs.

Data Types in PHP

PHP supports several data types. Let's explore each one:

1. String

A string is a sequence of characters enclosed in quotes:

<?php // Single quotes - literal string $name = 'John Doe'; // Double quotes - allows variable interpolation $greeting = "Hello, $name"; // Output: Hello, John Doe // Concatenation with dot operator $fullMessage = $greeting . " Welcome!"; // Multi-line string (heredoc syntax) $html = <<<HTML <div> <h1>Title</h1> <p>Content here</p> </div> HTML; ?>
Difference: Single quotes ('...') treat everything literally. Double quotes ("...") interpret variables and escape sequences like \n (newline).

2. Integer

Whole numbers without decimal points:

<?php $age = 25; // Positive integer $temperature = -5; // Negative integer $hex = 0x1A; // Hexadecimal (26 in decimal) $octal = 0755; // Octal notation $binary = 0b1010; // Binary (10 in decimal) // Large numbers (PHP 7.4+) $population = 7_500_000_000; // Underscore for readability ?>

3. Float (Double)

Numbers with decimal points:

<?php $price = 19.99; $temperature = -3.5; $scientific = 1.5e3; // Scientific notation (1500) $pi = 3.14159; ?>

4. Boolean

Represents true or false:

<?php $isActive = true; $hasAccess = false; // Commonly used in conditions if ($isActive) { echo "User is active"; } // Falsy values in PHP // false, 0, 0.0, "", "0", null, empty array ?>
Remember: The following values are considered false: false, 0, 0.0, "", "0", null, and empty arrays. Everything else is true.

5. Array

An ordered collection of values:

<?php // Indexed array (numeric keys) $colors = array("red", "green", "blue"); $fruits = ["apple", "banana", "orange"]; // Short syntax // Associative array (string keys) $person = [ "name" => "John", "age" => 25, "city" => "New York" ]; // Accessing array elements echo $colors[0]; // Output: red echo $person["name"]; // Output: John ?>

6. NULL

Represents a variable with no value:

<?php $value = null; // Explicitly set to null $notDefined; // Undefined variables are null // Checking for null if ($value === null) { echo "Value is null"; } // isset() checks if variable is set and not null if (isset($value)) { echo "Value is set"; } ?>

7. Object

An instance of a class (we'll cover this in detail later):

<?php class Person { public $name; public $age; } $john = new Person(); $john->name = "John"; $john->age = 25; ?>

Type Checking Functions

PHP provides functions to check variable types:

<?php $name = "John"; $age = 25; $price = 19.99; $isActive = true; $colors = ["red", "green"]; $value = null; // Type checking functions is_string($name); // true is_int($age); // true is_float($price); // true is_bool($isActive); // true is_array($colors); // true is_null($value); // true // Get variable type echo gettype($age); // Output: integer // Variable information (debugging) var_dump($age); // Output: int(25) ?>

Type Casting

You can convert variables from one type to another:

<?php $number = "123"; // String // Cast to integer $int = (int)$number; // 123 as integer $int = intval($number); // Alternative method // Cast to float $float = (float)"19.99"; // Cast to string $str = (string)123; // Cast to boolean $bool = (bool)1; // true $bool = (bool)0; // false // Cast to array $arr = (array)"hello"; // ["hello"] ?>
Be Careful: Type casting can lead to unexpected results. For example, (int)"10.5" becomes 10 (decimal part is lost).

Variable Scope

Variable scope determines where a variable can be accessed:

<?php // Global scope - accessible anywhere outside functions $globalVar = "I am global"; function testScope() { // Local scope - only accessible inside this function $localVar = "I am local"; // To access global variable inside function global $globalVar; echo $globalVar; // Alternative: use $GLOBALS superglobal echo $GLOBALS['globalVar']; } testScope(); echo $localVar; // ERROR: Undefined variable ?>

Constants

Constants are like variables but their values cannot change:

<?php // Define constant using define() define("SITE_NAME", "My Website"); define("MAX_USERS", 100); // Define constant using const keyword (PHP 5.3+) const API_KEY = "abc123xyz"; const TAX_RATE = 0.15; // Use constants (no $ sign) echo SITE_NAME; echo MAX_USERS; // Constants are global by default function showSiteName() { echo SITE_NAME; // Works without global keyword } // Check if constant exists if (defined("SITE_NAME")) { echo SITE_NAME; } ?>
Convention: Use UPPERCASE names for constants to distinguish them from variables. Use constants for values that never change, like configuration settings.

Variable Variables

PHP allows you to use the value of one variable as the name of another:

<?php $foo = "bar"; $$foo = "Hello"; // Creates $bar = "Hello" echo $bar; // Output: Hello echo $$foo; // Output: Hello // Practical example $field = "username"; $$field = "JohnDoe"; echo $username; // Output: JohnDoe ?>
Note: Variable variables are powerful but can make code harder to read. Use them sparingly and only when necessary.

Best Practices

✓ DO: - Use descriptive variable names - Follow consistent naming convention (camelCase or snake_case) - Initialize variables before use - Use constants for fixed values - Comment complex variable logic ❌ DON'T: - Use generic names like $data, $temp, $x (unless in loops) - Mix naming conventions - Reuse variables for different purposes - Use variable variables unnecessarily - Change variable types frequently

Practice Exercise:

Task: Create a PHP script that stores information about a product:

  • Product name (string)
  • Price (float)
  • Quantity in stock (integer)
  • Is available (boolean)
  • Display all information with appropriate labels
  • Calculate total value (price × quantity)

Solution:

<?php // Product information $productName = "Laptop"; $price = 999.99; $quantity = 15; $isAvailable = true; // Calculate total value $totalValue = $price * $quantity; // Display information echo "<h2>Product Information</h2>"; echo "<p><strong>Name:</strong> $productName</p>"; echo "<p><strong>Price:</strong> $" . number_format($price, 2) . "</p>"; echo "<p><strong>Quantity:</strong> $quantity</p>"; echo "<p><strong>Available:</strong> " . ($isAvailable ? "Yes" : "No") . "</p>"; echo "<p><strong>Total Value:</strong> $" . number_format($totalValue, 2) . "</p>"; ?>

Summary

In this lesson, you learned:

  • Variables are containers for storing data values
  • Variable names must start with $ and follow specific naming rules
  • PHP has 8 main data types: string, integer, float, boolean, array, object, resource, NULL
  • Use gettype() and is_*() functions to check variable types
  • Type casting converts variables between types
  • Variable scope determines where variables are accessible
  • Constants store values that never change
  • Use descriptive names and consistent conventions
Next Up: In the next lesson, we'll explore operators in PHP - how to perform calculations, comparisons, and logical operations with your variables!

ES
Edrees Salih
9 hours ago

We are still cooking the magic in the way!