Backend Development 15 min read

Understanding PHP Variables and Data Types

This article provides a comprehensive overview of PHP variables and its eight basic data types—including scalars, compound, and special types—explaining declaration rules, naming best practices, dynamic variables, strings, integers, floats, booleans, arrays, and objects to help beginners start programming with PHP.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP Variables and Data Types

When learning a new programming language, understanding how it handles data types and variables is essential. Data types and variables are fundamental, determining how data is stored and used in code.

Therefore, whether you are a PHP beginner or just starting programming and choosing PHP as your first language, understanding PHP's data types and variables is a good starting point.

Variables

In any programming language, data types determine how data can be stored and used, while variables provide a way to store data in memory.

What is a variable?

A variable is a label that can store data. Variable names may consist of letters, numbers, and underscores but cannot start with a number. Variable names are case‑sensitive.

How to declare a variable?

In PHP, a variable is declared by using the $ symbol followed by the variable name. For example, the following code declares a variable named $name that stores a string:

<code>$name = "Jordan Ulmer";</code>

If you are new to programming, remember the importance of descriptive, clear, and concise variable names so that anyone can understand what the variable contains.

For instance, the name $name is not very clear; it could refer to a username, a website name, or other data.

A better name is $userName , which clearly indicates that the variable holds a user's name. Other good names are $firstName and $lastName :

<code>$userName = "Jordan Ulmer";</code>

Or consider:

<code>$firstName = "Jordan";
$lastName = "Ulmer";</code>

PHP variable definition rules:

All variables must start with a dollar sign ($) followed by the variable name.

Variable names cannot start with a digit (though they may contain digits).

Variable names may contain only letters, digits, and underscores.

PHP variables are case‑sensitive.

Dynamic variables

Dynamic variables are a powerful feature in PHP that allow you to create variable names dynamically based on the value of another variable.

Example:

<code>$firstName = "Jordan";

// $firstName's value is "Jordan"
$$firstName = "Bob"; // creates $Jordan with value "Bob"
echo $Jordan; // outputs: Bob
</code>

Basic data types

In programming, core data types are called primitive types. PHP has eight basic data types, which can be divided into three sub‑categories.

Scalar types

These hold a single value.

String – stores text data.

Integer – stores whole numbers.

Float – stores floating‑point numbers.

Boolean – stores true or false.

Compound types

These can hold multiple values.

Array – stores a collection of related data.

Object – stores complex data structures.

Special types

Resource – references external resources such as files or database connections.

NULL – represents the absence of a value.

String

Strings are a data type used to store textual data. They can be enclosed in single or double quotes; there is no functional difference.

<code>$string = 'Hello';</code>

Or with double quotes:

<code>$string = "Hello";</code>

Single‑quoted vs double‑quoted strings in PHP

Single‑quoted strings are treated literally; variables are not interpolated.

<code>$firstName = "Jordan";
$string = 'Hello $firstName';
echo $string; // outputs: Hello $firstName
</code>

Double‑quoted strings allow variable interpolation.

<code>$firstName = "Jordan";
$string = "Hello $firstName";
echo $string; // outputs: Hello Jordan
</code>

Using strings in PHP

PHP provides built‑in functions for common string operations, such as converting case.

strtoupper() – converts a string to uppercase.

strtolower() – converts a string to lowercase.

Example:

<code>$firstName = "Jordan";
$upperCase = strtoupper($firstName);
$lowerCase = strtolower($firstName);
echo $upperCase, "<br>";
echo $lowerCase;
</code>

Output:

<code>JORDAN<br>jordan</code>

Other useful string functions include strlen() , substr() , str_replace() , and trim() .

Integer

Integers represent numeric values and can be decimal, octal, hexadecimal, or binary.

Decimal – e.g., 10, -10, 0.

Octal – prefixed with 0o or 0O.

Hexadecimal – prefixed with 0x or 0X.

Binary – prefixed with 0b or 0B.

Creating integer variables:

<code>$a = 10;      // decimal
$b = 0o10;    // octal
$c = 0x10;    // hexadecimal
$d = 0b10;    // binary
</code>

Float

Floats represent numbers with fractional parts and can be expressed in standard decimal notation or scientific notation.

<code>$floatNumber = 3.14;
$scientificFloat = 1.2e3;   // 1200.0
$smallFloat = 1.2e-3;      // 0.0012
</code>

Floating‑point arithmetic may suffer from precision issues, which is usually acceptable for most applications but important for scientific or financial calculations.

Boolean

Booleans represent true or false and are used in control structures such as if‑else statements and loops. In PHP, TRUE and FALSE are case‑insensitive, though the convention is uppercase. NULL , 0, and empty strings are also evaluated as false.

Array

Arrays are a fundamental data structure in PHP that allow storing and manipulating multiple values in a single variable. PHP supports indexed arrays and associative arrays.

Indexed arrays

Created with array() or square brackets:

<code>$arrayOfNames = array("Gale", "Karlach", "Astartion");
$arrayOfNames = ["Gale", "Karlach", "Astartion"];
</code>

Access elements by numeric index:

<code>$gale = $arrayOfNames[0];
echo $arrayOfNames[2]; // Astarion
</code>

Associative arrays

Store key‑value pairs:

<code>$arrayOfNames = array("Wizard" => "Gale", "Barbarian" => "Karlach", "Rogue" => "Astartion");
$arrayOfNames = ["Wizard" => "Gale", "Barbarian" => "Karlach", "Rogue" => "Astartion"];
</code>

Access elements by key:

<code>$gale = $arrayOfNames["Wizard"];
</code>

Arrays can contain nested arrays and objects, as shown in the following example of a multidimensional array:

<code>$baldursGate3Characters = [
    "playable" => [
        "Wizard" => "Gale",
        "Barbarian" => "Karlach",
        "Rogue" => "Astartion"
    ],
    "non-playable" => [
        "Gortash",
        "Ketherick",
        "Orrin"
    ]
];
var_dump($baldursGate3Characters);
</code>

Object

Objects are the core concept of object‑oriented programming (OOP). An object is an instance of a user‑defined class, which defines properties and methods.

Example class and object creation:

<code>class Car {
    public $color;
    public $size;

    public function move() {
        echo "Vroom!";
    }
}
$redCar = new Car();
$redCar->color = "red";
$redCar->size = "small";
</code>

This article provides an overview of PHP data types and variables to help beginners start their PHP learning journey.

ProgrammingPHPdata typesVariablesarraysstringsobjects
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.