PHP Variables and Data Types Explained

PHP Basics

Understanding variables and data types is essential for writing effective PHP code. In this guide, you'll learn how PHP variables work and explore the most common data types used in real-world applications.

What Is a Variable in PHP?

A variable in PHP is used to store data. Each variable starts with a dollar sign ($) followed by its name.

<?php
$name = "John";
$age = 25;

PHP is a loosely typed language, meaning you don’t need to declare the data type explicitly.

Variable Naming Rules

  • Must start with $
  • Must begin with a letter or underscore
  • Cannot start with a number
  • Case-sensitive ($name$Name)

PHP Data Types

1. String

A string is a sequence of characters.

$text = "Hello, PHP!";

2. Integer

An integer is a whole number.

$number = 100;

3. Float (Double)

A float is a number with a decimal point.

$price = 19.99;

4. Boolean

A boolean represents true or false.

$isActive = true;

5. Array

An array stores multiple values in a single variable.

$colors = ["red", "green", "blue"];

6. Object

An object is an instance of a class.

class User {
  public $name;
}

$user = new User();
$user->name = "John";

7. NULL

NULL represents a variable with no value.

$value = null;

8. Resource

A resource is a special variable that holds a reference to an external resource, such as a file, database connection, or stream.

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

In this example, $file is a resource pointing to an open file.

  • Common examples: file handles, database connections, cURL sessions
  • Resources should be closed after use (e.g., fclose())
  • Modern PHP often replaces resources with objects (e.g., PDO)

Checking Data Types

You can check the type of a variable using built-in functions:

var_dump($name);
gettype($name);

Type Casting in PHP

PHP allows you to convert variables from one type to another.

$num = "10";
$int = (int)$num;

Type Juggling vs Strict Types

PHP automatically converts types when needed (type juggling):

$result = "5" + 10; // 15

For stricter behavior, enable strict types:

declare(strict_types=1);

Best Practices

  • Use meaningful variable names
  • Avoid unnecessary type conversions
  • Enable strict types in modern PHP
  • Validate data types when needed

Common Mistakes

  • Using undefined variables
  • Mixing types unintentionally
  • Confusing null with empty values

FAQ

Do I need to declare variable types in PHP?

No, PHP is loosely typed, but you can enforce types in functions.

What is the difference between int and float?

Integers are whole numbers, while floats include decimals.

What is NULL in PHP?

NULL means a variable has no value assigned.

How do I check a variable type?

Use var_dump() or gettype().

Conclusion

PHP variables and data types are simple but powerful. Understanding them helps you write cleaner, safer, and more efficient code.