Skip to content

Data Types

Overview

PHP is a dynamically typed language, meaning variables don't require explicit type declarations. However, understanding PHP's data types is essential for writing robust applications. This chapter covers all PHP data types, type casting, type checking, and type declarations.

Scalar Types

Strings

Strings are sequences of characters used for storing and manipulating text.

php
<?php
// Single quotes - literal strings
$name = 'John Doe';
$message = 'Hello, World!';

// Double quotes - variable interpolation
$greeting = "Hello, $name!";
$path = "C:\Users\$name\Documents";

// Escape sequences in double quotes
$text = "First line\nSecond line\ttabbed";
$quote = 'He said "Hello"';

// String length
echo strlen($name); // 8

// String functions
echo strtoupper($name);    // JOHN DOE
echo strtolower($name);    // john doe
echo ucfirst($name);       // John Doe
echo ucwords($name);       // John Doe
?>

Heredoc and Nowdoc

php
<?php
$name = "Alice";

// Heredoc - similar to double quotes
$html = <<<HTML
<div class="user">
    <h1>Welcome, $name!</h1>
    <p>Variable interpolation is supported here.</p>
</div>
HTML;

// Nowdoc - similar to single quotes
$config = <<<'CONFIG'
server_name = localhost
database = myapp
user = $name  // This won't be interpolated
CONFIG;

echo $html;
echo $config;
?>

Integers

Integers are whole numbers without decimal points.

php
<?php
$decimal = 123;        // Decimal
$octal = 0123;         // Octal (83 in decimal)
$hex = 0x1A;           // Hexadecimal (26 in decimal)
$binary = 0b1010;      // Binary (10 in decimal, PHP 5.4+)

// Integer limits
echo PHP_INT_MAX;      // Maximum integer value
echo PHP_INT_MIN;      // Minimum integer value
echo PHP_INT_SIZE;     // Size in bytes

// Type checking
var_dump(is_int($decimal));     // true
var_dump(is_integer($decimal)); // true (alias)

// Integer operations
$a = 10;
$b = 3;
echo $a + $b;    // 13
echo $a - $b;    // 7
echo $a * $b;    // 30
echo $a / $b;    // 3.333... (becomes float)
echo $a % $b;    // 1 (modulo)
echo $a ** $b;   // 1000 (exponentiation, PHP 5.6+)
?>

Floats (Float/Double)

Floating-point numbers represent numeric values with decimal points.

php
<?php
$price = 19.99;
$scientific = 1.23e4;    // 12300
$negative = -3.14;

// Float precision issues
$result = 0.1 + 0.2;
var_dump($result);       // 0.30000000000000004
var_dump($result == 0.3); // false

// Correct float comparison
function floatEquals($a, $b, $epsilon = 0.00001) {
    return abs($a - $b) < $epsilon;
}

var_dump(floatEquals(0.1 + 0.2, 0.3)); // true

// Float functions
echo round(3.7);         // 4
echo floor(3.7);         // 3
echo ceil(3.2);          // 4
echo number_format(1234.567, 2); // "1,234.57"

// Type checking
var_dump(is_float($price));  // true
var_dump(is_double($price)); // true (alias)
?>

Booleans

Booleans represent true or false values.

php
<?php
$isActive = true;
$isComplete = false;

// Boolean casting
var_dump((bool) 1);        // true
var_dump((bool) 0);        // false
var_dump((bool) "");       // false
var_dump((bool) "0");      // false
var_dump((bool) "false");  // true (non-empty string)
var_dump((bool) []);       // false (empty array)
var_dump((bool) null);     // false

// Falsy values in PHP
$falsyValues = [
    false,
    0,
    0.0,
    "",
    "0",
    null,
    []
];

foreach ($falsyValues as $value) {
    if (!$value) {
        echo "This value is falsy\n";
    }
}

// Type checking
var_dump(is_bool($isActive)); // true
?>

Compound Types

Arrays

Arrays are ordered collections of values.

Indexed Arrays

php
<?php
// Creating indexed arrays
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5);

// Accessing elements
echo $fruits[0];  // "apple"
echo $fruits[1];  // "banana"

// Adding elements
$fruits[] = "grape";           // Append
$fruits[10] = "mango";         // Specific index
array_push($fruits, "kiwi");   // Append using function

// Array functions
echo count($fruits);           // Array length
echo sizeof($fruits);          // Alias for count()
var_dump(in_array("apple", $fruits)); // true

// Iterating arrays
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

foreach ($fruits as $index => $fruit) {
    echo "$index: $fruit\n";
}
?>

Associative Arrays

php
<?php
// Creating associative arrays
$person = [
    "name" => "John Doe",
    "age" => 30,
    "email" => "john@example.com",
    "active" => true
];

// Accessing elements
echo $person["name"];    // "John Doe"
echo $person["age"];     // 30

// Adding/modifying elements
$person["city"] = "New York";
$person["age"] = 31;

// Array functions
$keys = array_keys($person);       // Get all keys
$values = array_values($person);   // Get all values
var_dump(array_key_exists("name", $person)); // true

// Iterating associative arrays
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
?>

Multidimensional Arrays

php
<?php
$users = [
    [
        "id" => 1,
        "name" => "John",
        "email" => "john@example.com"
    ],
    [
        "id" => 2,
        "name" => "Jane",
        "email" => "jane@example.com"
    ]
];

// Accessing nested elements
echo $users[0]["name"];  // "John"
echo $users[1]["email"]; // "jane@example.com"

// Adding nested elements
$users[0]["age"] = 30;

// Iterating multidimensional arrays
foreach ($users as $user) {
    echo "ID: " . $user["id"] . "\n";
    echo "Name: " . $user["name"] . "\n";
    echo "Email: " . $user["email"] . "\n";
    echo "---\n";
}
?>

Array Operations

php
<?php
$numbers = [1, 2, 3, 4, 5];

// Array functions
$doubled = array_map(function($n) { return $n * 2; }, $numbers);
$evens = array_filter($numbers, function($n) { return $n % 2 == 0; });
$sum = array_reduce($numbers, function($carry, $n) { return $carry + $n; }, 0);

// Sorting
$fruits = ["banana", "apple", "orange"];
sort($fruits);           // Sort values
asort($fruits);          // Sort values, maintain keys
ksort($fruits);          // Sort by keys

// Merging and slicing
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$merged = array_merge($arr1, $arr2);  // [1, 2, 3, 4, 5, 6]
$slice = array_slice($numbers, 1, 3); // [2, 3, 4]

// Array searching
$position = array_search("apple", $fruits);
$exists = in_array("banana", $fruits);
?>

Objects

Objects are instances of classes that encapsulate data and behavior.

php
<?php
// Simple class definition
class Person {
    public $name;
    public $age;
    private $email;
    
    public function __construct($name, $age, $email) {
        $this->name = $name;
        $this->age = $age;
        $this->email = $email;
    }
    
    public function getEmail() {
        return $this->email;
    }
    
    public function setEmail($email) {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->email = $email;
        }
    }
    
    public function introduce() {
        return "Hello, I'm {$this->name} and I'm {$this->age} years old.";
    }
}

// Creating objects
$person1 = new Person("Alice", 25, "alice@example.com");
$person2 = new Person("Bob", 30, "bob@example.com");

// Accessing properties and methods
echo $person1->name;           // "Alice"
echo $person1->introduce();    // "Hello, I'm Alice and I'm 25 years old."
$person1->setEmail("alice.new@example.com");

// Object comparison
var_dump($person1 == $person2);  // false (different values)
var_dump($person1 === $person2); // false (different objects)

// Type checking
var_dump(is_object($person1));   // true
var_dump($person1 instanceof Person); // true
?>

stdClass Objects

php
<?php
// Creating stdClass objects
$obj = new stdClass();
$obj->name = "John";
$obj->age = 30;

// Converting array to object
$array = ["name" => "Jane", "age" => 25];
$obj2 = (object) $array;

echo $obj2->name; // "Jane"

// Converting object to array
$backToArray = (array) $obj2;
var_dump($backToArray); // ["name" => "Jane", "age" => 25]
?>

Special Types

NULL

NULL represents a variable with no value.

php
<?php
$var = null;
$undefined;  // Also null

// NULL assignment
$name = "John";
$name = null;  // Now null

// Type checking
var_dump(is_null($var));      // true
var_dump($var === null);      // true
var_dump(isset($var));        // false
var_dump(empty($var));        // true

// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
$config = $userConfig ?? $defaultConfig ?? 'fallback';

// Null coalescing assignment (PHP 7.4+)
$config ??= 'default_value';
?>

Resources

Resources are special variables holding references to external resources.

php
<?php
// File resource
$file = fopen('data.txt', 'r');
var_dump(is_resource($file)); // true
var_dump(get_resource_type($file)); // "stream"
fclose($file);

// Database resource (old MySQL extension)
// $connection = mysql_connect('localhost', 'user', 'pass');
// var_dump(is_resource($connection)); // true

// cURL resource
$curl = curl_init();
var_dump(is_resource($curl)); // true
curl_close($curl);

// Image resource (GD extension)
if (extension_loaded('gd')) {
    $image = imagecreate(100, 100);
    var_dump(is_resource($image)); // true
    imagedestroy($image);
}
?>

Type Casting and Type Juggling

Automatic Type Casting

php
<?php
// String to number
$str = "123";
$num = $str + 0;     // 123 (integer)
$float = $str + 0.0; // 123.0 (float)

// Arithmetic operations
echo "10" + "20";    // 30 (both cast to integers)
echo "10.5" + "20.3"; // 30.8 (both cast to floats)

// String concatenation
echo 10 . 20;        // "1020" (both cast to strings)

// Boolean context
if ("0") {           // false
    echo "This won't print";
}

if ("false") {       // true (non-empty string)
    echo "This will print";
}
?>

Explicit Type Casting

php
<?php
$value = "123.45";

// Casting to different types
$int = (int) $value;        // 123
$float = (float) $value;    // 123.45
$string = (string) $value;  // "123.45"
$bool = (bool) $value;      // true
$array = (array) $value;    // ["123.45"]
$object = (object) $value;  // stdClass with property "scalar" => "123.45"

// Using conversion functions
$int2 = intval($value);     // 123
$float2 = floatval($value); // 123.45
$string2 = strval($value);  // "123.45"

// Parsing functions
$parsed = parse_url("https://example.com/path?query=value");
$json = json_decode('{"name": "John", "age": 30}', true);
?>

Type Checking Functions

Built-in Type Checking

php
<?php
$var = "Hello";

// Type checking functions
var_dump(is_string($var));   // true
var_dump(is_int($var));      // false
var_dump(is_float($var));    // false
var_dump(is_bool($var));     // false
var_dump(is_array($var));    // false
var_dump(is_object($var));   // false
var_dump(is_null($var));     // false
var_dump(is_resource($var)); // false

// Generic type checking
var_dump(gettype($var));     // "string"

// Numeric checking
var_dump(is_numeric("123"));   // true
var_dump(is_numeric("12.3"));  // true
var_dump(is_numeric("abc"));   // false

// Scalar checking
var_dump(is_scalar($var));     // true (string, int, float, bool)
var_dump(is_scalar([]));       // false (array is not scalar)
?>

Custom Type Checking

php
<?php
function isPositiveInteger($value) {
    return is_int($value) && $value > 0;
}

function isValidEmail($email) {
    return is_string($email) && filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

function isAssociativeArray($array) {
    if (!is_array($array)) {
        return false;
    }
    return array_keys($array) !== range(0, count($array) - 1);
}

// Usage
var_dump(isPositiveInteger(5));        // true
var_dump(isPositiveInteger(-5));       // false
var_dump(isValidEmail("test@example.com")); // true
var_dump(isAssociativeArray(["a" => 1, "b" => 2])); // true
?>

Type Declarations (PHP 7+)

Scalar Type Declarations

php
<?php
// Enable strict types (optional)
declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

function divide(float $a, float $b): float {
    return $a / $b;
}

function greet(string $name): string {
    return "Hello, " . $name;
}

function isActive(bool $status): bool {
    return $status;
}

// Usage
echo add(5, 3);           // 8
echo divide(10.0, 3.0);   // 3.333...
echo greet("Alice");      // "Hello, Alice"
echo isActive(true);      // 1 (true)
?>

Class Type Declarations

php
<?php
class User {
    public $name;
    
    public function __construct(string $name) {
        $this->name = $name;
    }
}

class UserService {
    public function saveUser(User $user): bool {
        // Save user logic
        return true;
    }
    
    public function getUsers(): array {
        // Return array of users
        return [];
    }
}

// Usage
$user = new User("John");
$service = new UserService();
$result = $service->saveUser($user);
?>

Nullable Types (PHP 7.1+)

php
<?php
function findUser(?int $id): ?User {
    if ($id === null) {
        return null;
    }
    
    // Find user logic
    return new User("Found User");
}

// Union types (PHP 8.0+)
function processId(int|string $id): string {
    return "Processing ID: " . $id;
}

// Usage
$user = findUser(null);     // Returns null
$user = findUser(123);      // Returns User object
echo processId(123);        // "Processing ID: 123"
echo processId("abc");      // "Processing ID: abc"
?>

Handling Mixed Types

Handling Unknown Types

php
<?php
function processValue($value) {
    switch (gettype($value)) {
        case 'string':
            return strtoupper($value);
        case 'integer':
        case 'double':
            return $value * 2;
        case 'boolean':
            return $value ? 'Yes' : 'No';
        case 'array':
            return count($value);
        case 'object':
            return get_class($value);
        case 'NULL':
            return 'NULL value';
        default:
            return 'Unknown type';
    }
}

// Test different types
echo processValue("hello");     // "HELLO"
echo processValue(5);           // 10
echo processValue(true);        // "Yes"
echo processValue([1, 2, 3]);   // 3
echo processValue(new stdClass()); // "stdClass"
echo processValue(null);        // "NULL value"
?>

Type-Safe Functions

php
<?php
function safeAdd($a, $b) {
    if (!is_numeric($a) || !is_numeric($b)) {
        throw new InvalidArgumentException("Both arguments must be numeric");
    }
    
    return $a + $b;
}

function safeArrayAccess(array $array, $key, $default = null) {
    return array_key_exists($key, $array) ? $array[$key] : $default;
}

// Usage
try {
    echo safeAdd(5, 3);        // 8
    echo safeAdd("5", "3");    // 8
    echo safeAdd("a", "b");    // Throws exception
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage();
}

$data = ["name" => "John", "age" => 30];
echo safeArrayAccess($data, "name", "Unknown");     // "John"
echo safeArrayAccess($data, "email", "No email");   // "No email"
?>

Next Steps

Now that you understand PHP's data types, let's explore variables and constants in more detail in Variables and Constants.

Practice Exercises

  1. Create functions demonstrating type casting for different data types
  2. Build a data validator that checks multiple types and formats
  3. Implement type-safe functions using type declarations
  4. Create a utility class for safe type conversions
  5. Practice working with multidimensional arrays and objects

Understanding data types is fundamental to writing robust PHP applications!

Content is for learning and research only.