Web Analytics

PHP Data Types

Beginner~30 min read

PHP supports 10 different data types, each designed for specific kinds of information. Understanding data types is crucial for writing efficient and bug-free code. Let's explore each type and learn when to use them!

PHP Data Types Overview

PHP organizes its data types into three categories:

PHP Data Types Hierarchy
Category Types Description
Scalar int, float, string, bool Single values
Compound array, object, callable, iterable Multiple values
Special resource, NULL Unique purposes
Output
Click Run to execute your code
var_dump(): This function displays detailed information about a variable including its type and value. It's invaluable for debugging!

Scalar Types (Single Values)

1. Integer (int)

Whole numbers without decimal points, positive or negative:

<?php
$age = 25;           // Positive integer
$temperature = -10;  // Negative integer
$hex = 0xFF;         // Hexadecimal (255)
$octal = 0755;       // Octal (493)
$binary = 0b1010;    // Binary (10)
?>
Platform Range
32-bit -2,147,483,648 to 2,147,483,647
64-bit -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

2. Float (double)

Numbers with decimal points or in exponential form:

<?php
$price = 19.99;
$pi = 3.14159;
$scientific = 1.5e3;  // 1500
$negative = -2.5;
?>
Precision Warning: Floating-point numbers have limited precision. Never compare floats directly with ==. Use a small tolerance instead!

3. String

Sequence of characters enclosed in quotes:

<?php
$single = 'Single quotes';
$double = "Double quotes";
$name = "John";
$greeting = "Hello, $name!";  // Variable parsing
?>

4. Boolean (bool)

Represents true or false:

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

// These values are considered false:
// false, 0, 0.0, "", "0", [], null

// Everything else is true
?>

Compound Types (Multiple Values)

5. Array

Ordered collection of values:

<?php
// Indexed array
$colors = ["red", "green", "blue"];

// Associative array
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];

// Mixed array
$mixed = [1, "text", true, [1, 2, 3]];
?>

6. Object

Instances of classes:

<?php
class Person {
    public $name;
    public $age;
}

$user = new Person();
$user->name = "John";
$user->age = 30;
?>

7. Callable

Functions that can be called:

<?php
function greet($name) {
    return "Hello, $name!";
}

$callback = 'greet';
echo $callback("John");  // Calls greet("John")
?>

8. Iterable

Arrays or objects that can be iterated (PHP 7.1+):

<?php
function process(iterable $items) {
    foreach ($items as $item) {
        echo $item;
    }
}

process([1, 2, 3]);  // Works with arrays
?>

Special Types

9. Resource

References to external resources (files, databases):

<?php
$file = fopen("data.txt", "r");  // File resource
// $db = mysqli_connect(...);    // Database resource
fclose($file);
?>

10. NULL

Represents a variable with no value:

<?php
$empty = null;
$undefined;  // Also NULL

// These create NULL:
$var = null;
unset($var);
$notSet;
?>

Type Checking Functions

PHP provides functions to check variable types:

Function Checks For Example
is_int() Integer is_int(42) โ†’ true
is_float() Float is_float(3.14) โ†’ true
is_string() String is_string("hi") โ†’ true
is_bool() Boolean is_bool(true) โ†’ true
is_array() Array is_array([1,2]) โ†’ true
is_object() Object is_object($obj) โ†’ true
is_null() NULL is_null(null) โ†’ true
is_resource() Resource is_resource($file) โ†’ true
<?php
$age = 25;

if (is_int($age)) {
    echo "Age is an integer";
}

// Get type as string
echo gettype($age);  // Output: "integer"
?>

Common Mistakes

1. Comparing floats with ==

<?php
$a = 0.1 + 0.2;
$b = 0.3;

if ($a == $b) {  // โŒ May fail due to precision
    echo "Equal";
}

// โœ… Correct way
if (abs($a - $b) < 0.0001) {
    echo "Equal (within tolerance)";
}
?>

2. Confusing "0" and 0

<?php
$str = "0";
$num = 0;

if ($str == $num) {  // โœ… true (type juggling)
    echo "Equal with ==";
}

if ($str === $num) {  // โŒ false (different types)
    echo "This won't print";
}
?>

Summary

  • 10 Types: int, float, string, bool, array, object, callable, iterable, resource, NULL
  • Scalar: Single values (int, float, string, bool)
  • Compound: Multiple values (array, object, callable, iterable)
  • Special: Unique purposes (resource, NULL)
  • var_dump(): Shows type and value
  • gettype(): Returns type as string
  • is_*(): Functions to check specific types
  • Flexible: Variables can change types

What's Next?

Now that you know PHP's data types, let's explore Type Juggling - PHP's automatic type conversion system. You'll learn how PHP converts between types and when to use explicit type casting!