MasterPHP.in
PHP Tutorial

Variables, Data Types, and Constants


What is a Variable?

A variable is a named container that stores a value your program can use and change later. In PHP, every variable name starts with a dollar sign ($), which is one of the language's most recognizable features.


php

<?php
$name = "Rohan";
$age = 28;
$isDeveloper = true;

echo $name; // Rohan

Once a variable is declared, you can reassign it at any point in your script, and PHP will simply overwrite the previous value:


php

<?php
$score = 50;
echo $score; // 50

$score = 75;
echo $score; // 75

Rules for Naming Variables

PHP enforces a few strict rules about how variables can be named:

  • Must start with a dollar sign, followed by a letter or an underscore (not a number).
  • Can only contain letters, numbers, and underscores after the first character.
  • Are case-sensitive — $name and $Name are treated as two completely different variables.
  • Cannot contain spaces or special characters like - or @.


php

<?php
$user_name = "valid";
$_userName = "valid";
$userName2 = "valid";

// $2userName = "invalid";  // cannot start with a number
// $user-name = "invalid";  // hyphens are not allowed

Beyond the technical rules, it's worth following a consistent naming convention. Most PHP projects use camelCase ($firstName) or snake_case ($first_name) — either is fine, but staying consistent throughout a project makes code significantly easier to read and maintain.


PHP's Core Data Types

PHP is a loosely typed language, meaning you don't have to declare a variable's type upfront — PHP figures it out automatically based on the value assigned. Still, understanding each type is essential since they behave differently in calculations, comparisons, and functions.


php

<?php
$string  = "Hello, PHP";      // string - text data
$integer = 42;                // integer - whole numbers
$float   = 19.99;             // float (or "double") - decimal numbers
$boolean = true;               // boolean - true or false only
$array   = ["red", "green", "blue"]; // array - ordered collection of values
$null    = null;               // null - represents "no value"

String

A string is any sequence of characters, wrapped in single or double quotes. Strings are covered in depth in the previous lesson, but as a data type, they're used for anything text-based — names, messages, addresses, and so on.

Integer

Integers are whole numbers, positive or negative, without a decimal point.


php

<?php
$temperature = -5;
$totalUsers = 1500;

Float (Double)

Floats represent numbers with decimal points, used whenever precision beyond whole numbers matters — prices, percentages, measurements.


php

<?php
$price = 499.50;
$gpa = 3.75;

Boolean

Booleans hold only one of two values: true or false. They're the backbone of conditions and control flow, determining which path your code takes.


php

<?php
$isLoggedIn = true;
$hasPermission = false;

Array

An array stores multiple values inside a single variable, either as an indexed list or as key-value pairs.


php

<?php
$fruits = ["apple", "banana", "mango"]; // indexed array
$user = ["name" => "Rohan", "age" => 28]; // associative array

Arrays are a large enough topic to warrant their own dedicated lesson later in this series, so this is just an introduction to recognizing them as a data type.

NULL

null represents the deliberate absence of a value — different from an empty string or zero, both of which are still "something." A variable holding null is essentially saying "this exists, but has no value assigned."


php

<?php
$middleName = null;

Checking a Variable's Type

Since PHP determines types automatically, it's often useful to verify what type a variable currently holds, especially when debugging:


php

<?php
$value = "25";

echo gettype($value);       // string
var_dump($value);           // string(2) "25"

var_dump(is_string($value));  // true
var_dump(is_int($value));     // false
var_dump(is_array($value));   // false

var_dump() is one of the most useful debugging tools in PHP — it shows both the type and value of a variable, which echo alone can't do.


Type Juggling: PHP's Automatic Conversion

Because PHP is loosely typed, it sometimes converts values automatically during operations — a behavior known as type juggling.


php

<?php
$result = "5" + 3;   // 8 - PHP converts "5" to an integer automatically
$result2 = "5" . 3;  // "53" - the . operator forces string concatenation instead

This automatic behavior is convenient but can also cause subtle bugs if you're not paying attention to which operator you're using — + triggers numeric conversion, while . triggers string conversion, even when working with the exact same values.


What is a Constant?

A constant is similar to a variable in that it stores a value, but with one key difference: once defined, its value cannot be changed anywhere else in the script. Constants are used for values that should remain fixed throughout your application — configuration settings, API keys, fixed rates, or application-wide labels.


php

<?php
define("SITE_NAME", "MasterPHP");
echo SITE_NAME; // MasterPHP

// define("SITE_NAME", "Something Else"); // this would trigger a warning/error

Notice that constants don't use a dollar sign, and by strong convention, are written in uppercase letters with underscores separating words.


Defining Constants with const

PHP also supports a second way to define constants, using the const keyword, which is more common inside classes:


php

<?php
const MAX_LOGIN_ATTEMPTS = 5;
echo MAX_LOGIN_ATTEMPTS; // 5

define() vs const: Key Differences


Feature                    define()              const
------------------------------------------------------------
Can be used inside a       No                    Yes
class?
Can be defined              Yes                   No (must be a
conditionally (inside                              fixed value known
an if statement)?                                  at compile time)
Evaluated at                Runtime               Compile time
Common use case             Global app config     Class-level fixed
                                                    values

For most beginner projects, define() is simpler to reach for outside of classes, while const becomes more relevant once you start working with object-oriented PHP later in this series.


Variables vs Constants: Quick Comparison


Aspect              Variable ($name)         Constant (NAME)
------------------------------------------------------------
Symbol               Starts with $            No symbol prefix
Value can change?    Yes                      No, fixed once set
Naming convention     camelCase/snake_case     UPPER_CASE
Scope behavior        Follows scope rules      Globally accessible

What's Next

With a solid grasp of variables, data types, and constants, you're ready to explore how PHP makes decisions using these values — which is exactly what control flow (if statements, switch, and match) covers in the next part of this series.

Frequently Asked Questions

No. PHP is a loosely typed language, meaning it automatically determines a variable's type based on the value you assign to it. You can change what a variable holds later, and PHP will adjust its type accordingly.
A variable's value can be changed anywhere in your script after it's declared, while a constant's value is fixed once defined and cannot be changed. Constants also don't use a dollar sign and are conventionally written in uppercase.
This is simply PHP's syntax rule — constants defined with define() or const are referenced by name only, without the $ prefix that variables require. It's a quick visual way to distinguish constants from regular variables in your code.
Type juggling refers to PHP automatically converting a value from one data type to another during an operation, based on context. For example, using + between a numeric string and a number triggers automatic conversion to perform arithmetic.
No. null represents the complete absence of a value, while an empty string ("") and zero (0) are still defined values of their respective types. All three are treated as "falsy" in conditions, but they are distinct values with different meanings.

Share this tutorial