1. php
  2. /basics
  3. /data-types

Introduction to PHP data-types

List of Data Types

In PHP, there are several data types that can be used to store different types of values. Some common data types include:

Understanding PHP's Type System

PHP uses a dynamic type system where variables can hold values of any type and can change types during execution. This flexibility comes from PHP's internal type juggling system, which automatically converts between types as needed. Understanding each data type's characteristics, limitations, and use cases is crucial for writing robust PHP applications.

  1. Integer: A whole number, such as -5, 0, or 25.

    Integer Details:

    • Range: Platform-dependent, typically -2,147,483,648 to 2,147,483,647 on 32-bit systems
    • On 64-bit systems: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    • Overflow behavior: Automatically converts to float when exceeding limits
    • Notation support: Decimal, hexadecimal (0x), octal (0), and binary (0b)
    • Common operations: Arithmetic, bitwise operations, comparisons
  2. Float: A decimal number, such as 3.14 or -0.5.

    Float Characteristics:

    • Also known as "double" or "real" numbers
    • Precision: Typically 14 decimal digits (platform-dependent)
    • Special values: INF (infinity), -INF, and NAN (not a number)
    • Warning: Floating-point arithmetic can have precision issues
    • Never compare floats for equality directly; use epsilon comparison
    • Scientific notation supported: 1.2e3 equals 1200
  3. String: A sequence of characters, such as "Hello World!" or "John Smith".

    String Properties:

    • No practical size limit (limited by available memory)
    • Internally stored as byte arrays
    • Can contain any binary data, including null bytes
    • Encoding-agnostic (but UTF-8 recommended)
    • Supports variable interpolation in double quotes
    • Extensive built-in function library for manipulation
  4. Boolean: A true or false value, used for conditional statements and logic.

    Boolean Behavior:

    • Only two values: true and false (case-insensitive)
    • Type juggling: Many values convert to boolean in conditions
    • Falsy values: false, 0, 0.0, "", "0", [], NULL
    • Everything else is truthy
    • Common pitfall: The string "false" is truthy!
  5. Array: A collection of values that can be accessed by an index or key.

    Array Features:

    • Can be indexed (numerical keys) or associative (string keys)
    • Mixed keys allowed in same array
    • Dynamic sizing - grows and shrinks automatically
    • Preserves insertion order (since PHP 7)
    • Multi-dimensional arrays supported
    • Rich set of array functions for manipulation
  6. Object: An instance of a class, which can have properties and methods.

    Object Characteristics:

    • Created from classes using new keyword
    • Pass-by-reference semantics (actually object identifiers)
    • Supports inheritance, interfaces, and traits
    • Can implement magic methods for special behavior
    • Type hinting supported in function parameters
    • Garbage collected when no references remain
  7. NULL: A value that represents the absence of a value.

    NULL Semantics:

    • Single value: NULL (case-insensitive)
    • Represents: uninitialized variables, explicit absence
    • Results from: unset(), functions with no return
    • Type juggling: Converts to empty string, 0, or false
    • Checking: Use is_null() or === null
    • Different from empty string or zero
  8. Resource: A special type of data that represents a connection to an external resource, such as a file or database connection.

    Resource Management:

    • Created by specific functions (fopen, mysql_connect, etc.)
    • Cannot be created directly in PHP code
    • Automatically freed when no longer referenced
    • Check type with get_resource_type()
    • Common types: file handles, database connections, image resources
    • Always close explicitly when done for better resource management
  9. Callback: A function or method that can be passed as an argument to another function.

    Callback Types:

    • String containing function name
    • Array with object/class and method name
    • Anonymous functions (closures)
    • Arrow functions (PHP 7.4+)
    • Invokable objects (implementing __invoke)
    • Type hint with callable for parameters
  10. Mixed: A variable that can store different types of data, such as integers, strings, or arrays.

    Mixed Type Usage:

    • Not an actual PHP type until PHP 8.0
    • In PHP 8.0+: Explicit type declaration for "any type"
    • Represents PHP's dynamic typing nature
    • Use when type truly varies or is unknown
    • Consider union types (PHP 8.0+) for specific type sets
    • Document expected types for better code clarity

Examples

Practical Data Type Usage

Here are examples of how some of the PHP data types can be used:

<?php
// Integer
$age = 25;

Integer Examples Explained:

  • Direct assignment creates integer type
  • Can use different notations: $hex = 0xFF; (255), $octal = 0755; (493)
  • Type checking: is_int($age) returns true
  • Casting: (int) or intval() converts other types
// Float
$pi = 3.14;

Float Precision Considerations:

  • Avoid exact comparisons: $pi == 3.14 might fail
  • Use epsilon comparison: abs($pi - 3.14) < 0.00001
  • Format for display: number_format($pi, 2) shows "3.14"
  • Scientific notation: $avogadro = 6.022e23;
// String
$name = "John Smith";

String Manipulation Options:

  • Length: strlen($name) returns 10
  • Substring: substr($name, 0, 4) returns "John"
  • Case conversion: strtoupper($name) returns "JOHN SMITH"
  • Concatenation: $fullName = $name . ", Jr.";
// Boolean
$isStudent = true;

Boolean Usage Patterns:

  • Direct use in conditions: if ($isStudent) { ... }
  • Negation: $isNotStudent = !$isStudent;
  • From comparison: $isAdult = $age >= 18;
  • String representation: var_export($isStudent) shows "true"
// Array
$colors = array("red", "green", "blue");

Array Operations:

  • Modern syntax: $colors = ["red", "green", "blue"];
  • Access elements: $colors[0] returns "red"
  • Add elements: $colors[] = "yellow"; or array_push($colors, "yellow");
  • Count elements: count($colors) returns 3
  • Check existence: in_array("green", $colors) returns true
// Object
class Person {
    public $name;
    public $age;
}
$person = new Person();
$person->name = "Jane Doe";
$person->age = 30;

Object-Oriented Features:

  • Property access: $person->name or $person->{'name'}
  • Method calls: $person->getName() if method exists
  • Type checking: $person instanceof Person returns true
  • Cloning: $clone = clone $person; creates shallow copy
  • Serialization: serialize($person) for storage
// NULL
$address = NULL;

NULL Handling Patterns:

  • Null coalescing: $value = $address ?? "No address"; (PHP 7+)
  • Null safe operator: $city = $address?->city; (PHP 8+)
  • Default assignment: $address ??= "Unknown"; (PHP 7.4+)
  • Existence check: isset($address) returns false
// Resource
$file = fopen("example.txt", "r");

Resource Best Practices:

  • Always check for failure: if ($file === false) { ... }
  • Use with error suppression carefully: @fopen(...)
  • Close when done: fclose($file);
  • Check resource type: get_resource_type($file) returns "stream"
  • Automatic cleanup: Resources freed at script end
// Callback
function sayHello() {
    echo "Hello World!";
}
$callback = "sayHello";

Callback Invocation Methods:

  • Direct call: $callback();
  • Using call_user_func: call_user_func($callback);
  • With parameters: call_user_func_array($callback, $params);
  • Anonymous function: $callback = function() { echo "Hello!"; };
  • Type checking: is_callable($callback) returns true
// Mixed
$mixed = "Hello";
$mixed = 35;
$mixed = array(1, 2, 3);
?>

Type Flexibility Implications:

  • Each assignment changes the variable's type
  • Previous type/value is lost
  • Type checking: gettype($mixed) returns current type
  • Debugging: var_dump($mixed) shows type and value
  • Performance: Type changes have small overhead

In this example, we can see different data types being used in different ways. We can assign different values to different variables using different data types and call them in the program as per the requirement.

Type Juggling and Comparisons

PHP automatically converts types in many contexts:

Implicit Type Conversion

$number = "5";        // string
$result = $number + 2; // $number converted to int, result is 7
$concat = $number . 2; // 2 converted to string, result is "52"

Comparison Operators

  • == : Loose comparison (with type juggling)
  • === : Strict comparison (no type juggling)
  • != : Loose not equal
  • !== : Strict not equal

Common Juggling Pitfalls

"0" == false    // true (loose comparison)
"0" === false   // false (strict comparison)
[] == false     // true
[] === false    // false
"php" == 0      // true (string converts to 0)

Best Practices

  1. Always use the appropriate data type for the information you are storing. For example, use integers for whole numbers and floats for decimal numbers.

    Type appropriateness ensures predictable behavior and better performance. Using strings for numbers requires constant conversion and can lead to unexpected results. Choose types that match your data's nature and intended operations.

  2. Use proper variable naming conventions. For example, use camelCase for variable names and start variable name with lowercase letter.

    Consistent naming improves readability. Consider prefixing to indicate type when helpful: $isActive (boolean), $userCount (integer), $productList (array). This self-documenting approach reduces confusion.

  3. Avoid using hardcoded values in your code. Instead, use constants or variables to store values that may change in the future.

    Magic numbers and strings make code hard to maintain. Define constants for fixed values: const MAX_USERS = 100;. This centralizes configuration and makes changes easier.

  4. When working with strings, make sure to use the appropriate string functions for the task at hand. For example, use the strlen() function to find the length of a string and str_replace() to replace a specific substring.

    PHP offers specialized functions optimized for specific tasks. Using the right function improves performance and code clarity. For multibyte strings, use mb_* functions.

  5. Be mindful of the size and memory usage of your arrays. Use the appropriate data structures, such as linked lists or hash tables, to optimize performance.

    Large arrays consume significant memory. Consider using generators for large datasets, SplFixedArray for fixed-size arrays, or database queries with LIMIT for pagination.

  6. When working with objects, take advantage of the object-oriented features of PHP, such as inheritance and polymorphism.

    OOP provides better code organization and reusability. Use interfaces for contracts, abstract classes for shared behavior, and traits for horizontal reuse.

  7. Use NULL values appropriately, to indicate when a variable has no value assigned to it.

    NULL explicitly represents absence. Don't use empty strings or zero as substitutes. This distinction helps in validation and business logic.

  8. When working with resources, make sure to close them properly when they are no longer needed.

    Unclosed resources can cause memory leaks and hit system limits. Use try-finally blocks or better yet, use modern APIs that handle resources automatically.

  9. When working with callbacks, make sure that the function or method being passed as a callback is valid and can be called.

    Always validate callbacks with is_callable() before invoking. This prevents fatal errors and provides better error messages.

  10. Be consistent in your data types usage, avoid mixing data types for the same kind of information, for example, don't use string for storing age and integer for storing name.

    Type consistency prevents bugs and improves code predictability. If age is an integer in one place, it should be an integer everywhere. Document expected types in comments or use type declarations.