PHP Data Types

PHP is a dynamically typed language, which means you don't need to explicitly declare the type of a variable when you create it. However, understanding PHP's data types and using them consistently is important for writing reliable and maintainable code.

PHP supports several data types, which can be categorized into scalar types, compound types, and special types.

Scalar Types

Scalar types hold a single value and are the building blocks of more complex data structures.

1. String

Strings represent text data and can be defined using single quotes, double quotes, or heredoc/nowdoc syntax.

php
$singleQuoted = 'Hello World';
$doubleQuoted = "Hello World";
$name = "Josh";
$greeting = "Hello, $name!"; // Variable interpolation with double quotes

echo $greeting; // Output: Hello, Josh!

Key difference: Double quotes allow variable interpolation, while single quotes treat everything literally.

2. Integer

Integers are whole numbers without decimal points.

php
$positive = 42;
$negative = -17;
$octal = 0123;     // Octal (base 8)
$hex = 0x1A;       // Hexadecimal (base 16)
$binary = 0b1010;  // Binary (base 2)

echo $binary; // Output: 10 (decimal equivalent)

3. Float (Double)

Floating-point numbers represent decimal values.

php
$price = 19.99;
$scientific = 1.23e4; // Scientific notation (12300)
$percentage = 0.15;

echo $scientific; // Output: 12300

4. Boolean

Booleans represent true/false values and are case-insensitive.

php
$isActive = true;
$isComplete = false;
$isValid = TRUE; // Also valid

// Common falsy values in PHP
$empty = false;
$zero = 0;
$emptyString = "";
$null = null;

if ($isActive) {
    echo "User is active";
}

Compound Types

Compound types can hold multiple values.

1. Array

Arrays can store multiple values and can be indexed or associative.

php
// Indexed array
$fruits = ["apple", "banana", "orange"];
$numbers = [1, 2, 3, 4, 5];

// Associative array
$person = [
    "name" => "Josh Reed",
    "age" => 30,
    "city" => "Denver"
];

// Accessing array elements
echo $fruits[0];        // Output: apple
echo $person["name"];   // Output: Josh Reed

// Mixed array
$mixed = [
    "name" => "Product A",
    "price" => 29.99,
    "tags" => ["electronics", "gadget"],
    "inStock" => true
];

2. Object

Objects are instances of classes and represent complex data structures.

php
class User {
    public $name;
    public $email;
    
    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }
    
    public function greet() {
        return "Hello, I'm " . $this->name;
    }
}

$user = new User("Josh Reed", "josh@example.com");
echo $user->greet(); // Output: Hello, I'm Josh Reed

Special Types

1. NULL

NULL represents a variable with no value.

php
$empty = null;
$undefined; // Uninitialized variables are NULL

// Checking for NULL
if (is_null($empty)) {
    echo "Variable is null";
}

// Alternative syntax
if ($empty === null) {
    echo "Variable is null";
}

2. Resource

Resources are special variables that hold references to external resources (like file handles or database connections).

php
// Opening a file creates a resource
$file = fopen("data.txt", "r");

if (is_resource($file)) {
    echo "File opened successfully";
    fclose($file);
}

Type Juggling and Casting

PHP automatically converts between types when needed, but you can also explicitly cast types.

php
// Automatic type conversion
$number = "10";
$result = $number + 5; // PHP converts "10" to integer 10
echo $result; // Output: 15

// Explicit type casting
$string = "123.45";
$integer = (int) $string;    // 123
$float = (float) $string;    // 123.45
$boolean = (bool) $string;   // true

echo $integer; // Output: 123

Type Checking Functions

PHP provides several functions to check variable types:

php
$value = "Hello World";

var_dump(gettype($value));     // string
var_dump(is_string($value));   // bool(true)
var_dump(is_int($value));      // bool(false)
var_dump(is_array($value));    // bool(false)
var_dump(is_object($value));   // bool(false)
var_dump(is_null($value));     // bool(false)
var_dump(is_bool($value));     // bool(false)
var_dump(is_float($value));    // bool(false)

Practical Example: Data Validation

Here's a practical example showing how understanding data types helps with validation:

php
function validateUserData(array $data): array {
    $errors = [];
    
    // Check if name is a non-empty string
    if (!isset($data['name']) || !is_string($data['name']) || empty(trim($data['name']))) {
        $errors[] = "Name must be a non-empty string";
    }
    
    // Check if age is a positive integer
    if (!isset($data['age']) || !is_int($data['age']) || $data['age'] <= 0) {
        $errors[] = "Age must be a positive integer";
    }
    
    // Check if email is a valid string
    if (!isset($data['email']) || !is_string($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Email must be a valid email address";
    }
    
    // Check if active status is boolean
    if (isset($data['active']) && !is_bool($data['active'])) {
        $errors[] = "Active status must be a boolean";
    }
    
    return $errors;
}

// Usage
$userData = [
    'name' => 'Josh Reed',
    'age' => 30,
    'email' => 'josh@example.com',
    'active' => true
];

$errors = validateUserData($userData);

if (empty($errors)) {
    echo "Data is valid!";
} else {
    foreach ($errors as $error) {
        echo "Error: $error\n";
    }
}

Type Declarations (PHP 7+)

Modern PHP allows you to declare parameter and return types for better code clarity and error prevention:

php
function calculateArea(float $length, float $width): float {
    return $length * $width;
}

function processUser(User $user): string {
    return $user->greet();
}

// Nullable types (PHP 7.1+)
function findUser(?int $id): ?User {
    if ($id === null) {
        return null;
    }
    // Logic to find user...
    return new User("Found User", "user@example.com");
}

Summary

Understanding PHP data types is essential for:

  • Writing predictable code: Knowing what type of data you're working with prevents unexpected behavior
  • Debugging effectively: Type-related errors are easier to spot when you understand the type system
  • Performance optimization: Appropriate use of types can improve memory usage and execution speed
  • Code maintainability: Type declarations make your code self-documenting and easier for others to understand

Key takeaways:

  • PHP has scalar types (string, int, float, bool), compound types (array, object), and special types (null, resource)
  • PHP performs automatic type conversion, but explicit casting gives you more control
  • Use type checking functions (is_string(), is_int(), etc.) for validation
  • Modern PHP supports type declarations for better code quality

Thanks for reading! Understanding these fundamentals will make you a more effective PHP developer and help you write more robust applications.