← Back to Chapters

PHP Variables

? PHP Variables

✨ Quick Overview

PHP variables are containers used to store data such as text, numbers, and decimal values. They begin with a dollar sign and are dynamically typed.

?️ Interactive Playground

Change the values below to see how PHP handles variable assignment and interpolation.

$userName = "Alex"; $userAge = 24; echo "Welcome back, $userName! You are $userAge.";
Output: Welcome back, Alex! You are 24.

? What is a Variable?

A variable in PHP is a container for storing information. It starts with a dollar sign ($), followed by the variable name.

?️ Declaring Variables

Variables are declared and assigned using the = operator. PHP automatically detects the data type.

? View Code Example
// Declaring variables of different data types
<?php
$txt = "Hello PHP";
$number = 25;
$price = 99.99;

echo $txt;
echo "<br>";
echo $number;
echo "<br>";
echo $price;
?>

? Variable Naming Rules

  • A variable name must start with a $ sign, followed by a letter or underscore.
  • Cannot start with a number.
  • Can only contain alphanumeric characters and underscores (A-z, 0-9, _).
  • Variable names are case-sensitive ($value and $Value are different).

? Using Variables

? View Code Example
// Using variables inside a string with interpolation
<?php
$name = "John";
$age = 30;

echo "My name is $name and I am $age years old.";
?>

? Live Output / Explanation

The variables $name and $age are replaced with their values directly inside the double-quoted string.

 

? Use Cases

  • Storing user input from forms
  • Holding calculation results
  • Managing configuration values
  • Dynamic content generation

✅ Tips & Best Practices

  • Use descriptive names (e.g., $totalPrice, $userName).
  • Use double quotes for variable interpolation (e.g., "Hello $name").
  • Use var_dump() to inspect variable types and values.

? Try It Yourself

  • Create a file named variables.php.
  • Define variables for your name, age, and favorite color.
  • Use echo to print a sentence using those variables.
  • Run the file using http://localhost/variables.php.