PHP

📦 What Are PHP Variables?

In PHP, variables act as temporary storage containers for holding data values such as text strings, numbers, arrays, or objects. Once stored, variable values can be accessed, manipulated, or updated throughout script execution.

  • In Short: Variable = A named container stored in memory to hold data.

1️⃣ How to Declare a Variable in PHP

Variables in PHP always begin with a dollar sign ($), followed immediately by the variable name. The assignment operator (=) assigns a value to the variable.

CSS

<?php
$txt = "Hello World!";
$x = 5;
$y = 10.5;
?>

2️⃣ Essential Rules for PHP Variables

When naming and defining variables, you must follow these syntax rules:

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

3️⃣ Loosely Typed Language Advantage

PHP is a dynamically (loosely) typed language. Unlike languages such as Java or C++, you do not need to explicitly declare the data type of a variable before assigning a value. PHP automatically converts and interprets the data type based on the assigned value.

CSS

<?php
$name = "Volkan"; // Automatically treated as String
$year = 2026; // Automatically treated as Integer
$price = 19.99; // Automatically treated as Float
$is_active = true; // Automatically treated as Boolean
?>

4️⃣ Outputting and Joining Variables

You can output variables directly using the echo construct or join them with strings using the concatenation dot (.) operator:

<?php
$txt = "teachwebcode.com";
echo "I love " . $txt . "!";
?>

  • Browser Output: I love teachwebcode.com!

🌐 PHP Variable Scope Overview

The scope of a variable defines the part of the script where the variable can be referenced or used. PHP has three main variable scopes:

  • Local: Variables declared within a function exist only inside that specific function.
  • Global: Variables declared outside functions. Accessing them inside functions requires the global keyword.
  • Static: Retains its value even after function execution completes using the static keyword.
  • 📝 Brief Summary

  • Variables always begin with a dollar sign ($) and must start with a letter or underscore.
  • PHP variables are case-sensitive and dynamically typed.
  • You can concatenate strings and variables seamlessly using the dot (.) operator.