Skip to main content

PHP Data Types

Data types determine what kind of data a variable can store.

PHP is dynamically typed.

Example:

$name = "Aayan";
$age = 18;

PHP automatically determines types.


Why Data Types Matter

Data types help:

✅ Prevent Bugs

✅ Improve Performance

✅ Better Memory Usage

✅ Type Safety


PHP Data Types

PHP supports:

  1. String
  2. Integer
  3. Float
  4. Boolean
  5. Array
  6. Object
  7. NULL
  8. Resource
  9. Callable
  10. Mixed

String

Strings store text.

$name = "Aayan";

Single Quotes

$name = 'Aayan';

Double Quotes

$name = "Aayan";

Supports interpolation:

echo "Hello $name";

Output:

Hello Aayan

Integer

Stores whole numbers.

$players = 150;

Examples:

10
-25
5000

Integer Limits

echo PHP_INT_MAX;

64-bit:

9223372036854775807

Float

Stores decimal numbers.

$price = 99.99;

Examples:

1.5
10.75
0.99

Boolean

Stores:

true
false

Example:

$isOnline = true;

Array

Stores multiple values.

$players = [
"Steve",
"Alex"
];

Indexed Arrays

$numbers = [1,2,3];

Associative Arrays

$user = [
"name" => "Aayan",
"age" => 18
];

Multidimensional Arrays

$servers = [
[
"name" => "Lobby"
]
];

Object

Objects are instances of classes.

class User {

}

$user = new User();

NULL

Represents no value.

$data = null;

Resource

Special type for external resources.

Example:

$file =
fopen("test.txt", "r");

Callable

Represents executable functions.

function hello() {

}

$fn = "hello";

Mixed

Can store any type.

function test(
mixed $value
) {

}

Checking Types


gettype()

echo gettype($name);

var_dump()

var_dump($name);

Output:

string(5) "Aayan"

is_string()

is_string($name);

is_int()

is_int($age);

is_bool()

is_bool(true);

is_array()

is_array([]);

Type Declaration

Modern PHP uses strict types.

function add(
int $a,
int $b
): int {

}

Union Types

function test(
int|string $value
) {

}

Nullable Types

?string

Example:

function getName():
?string {

}

Memory Representation

String  → Text
Integer → Numbers
Boolean → True/False
Array → Multiple Values
Object → Class Instance

PocketMine Examples

Player object:

Player

Configuration:

array

Health:

int

Movement speed:

float

Best Practices

✅ Always use type hints.

public function test(
string $name
): void {

}

❌ Avoid:

function test($a) {

}

Exercises

Create variables:

$name
$age
$health
$isOnline
$players

Quiz

Which type stores text?

Answer

String


Which type stores decimals?

Answer

Float


Which type stores multiple values?

Answer

Array


Mini Project

Create:

$name
$players
$money
$isOnline

Print them using:

var_dump();

References

https://www.php.net/manual/en/language.types.php


Next Chapter

➡ PHP Type Casting