OnlineCBT Logo OnlineCBT
PHP · LESSON 3

Variables, Scope, and Data Types

By Ratan Updated: 16 Oct 2026

Declare variables ($var), explore primitive data types, and understand local vs global vs static scope.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. Variables in PHP

A variable in PHP is a named memory container for storing data values. In PHP, variables always begin with the dollar sign ($) followed by the variable name.

Variable Naming Rules:

  • A variable name must start with a letter or an underscore (_).
  • It cannot start with a number (e.g., $1item is invalid).
  • It can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
  • Variable names are case-sensitive ($age and $Age are distinct).

2. PHP Data Types

PHP is a dynamically typed language (it automatically determines the type based on the assigned value). PHP data types are divided into three major categories:

A. Scalar Types

  • Integer: Non-decimal numbers between -2,147,483,648 and 2,147,483,647 (32-bit systems) or larger (64-bit systems). Example: $score = 98;
  • Float (Double): Numbers with decimal points or exponential forms. Example: $rating = 4.85;
  • String: Sequences of characters. Example: $name = "Rahul Sharma";
  • Boolean: Represents truth values: true or false.

B. Compound Types

  • Array: A collection of multiple values under a single name. Example: $skills = ["PHP", "MySQL", "JavaScript"];
  • Object: An instance of a programmer-defined class containing properties and methods.

C. Special Types

  • NULL: A variable with no assigned value or explicitly set to null.
  • Resource: Special handler referencing external resources (such as an open file stream or database connection).

3. Variable Scope

Scope refers to the context within which a variable is accessible:

  1. Local Scope: Variables declared within a function can only be accessed within that function.
  2. Global Scope: Variables declared outside any function have global scope and can be accessed anywhere outside functions. To access them inside a function, use the global keyword or $GLOBALS array.
  3. Static Scope: When a function executes, its local variables are normally deleted. Declaring a variable as static preserves its value across multiple function calls.
";
}

function countVisits() {
    static $visitCount = 0; // Preserves value
    $visitCount++;
    echo "Visit count: " . $visitCount . "
"; } countVisits(); // 1 countVisits(); // 2 countVisits(); // 3

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat