Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
PHP Basics 6 mins read Free Lesson

PHP Variables

Understand how variables work in PHP, naming rules, data types, variable scope, and type declaration.

PHP Variables

In PHP, variables are "containers" for storing data such as text strings, numbers, or complex objects.


Declaring PHP Variables

A variable starts with the $ sign, followed by the name of the variable:

<?php
$siteName = "E-Tutorial";
$studentCount = 15000;
$rating = 4.9;
$isPro = true;

echo "Welcome to " . $siteName . " with " . $studentCount . " active students!";
?>

Output

Welcome to E-Tutorial with 15000 active students!

Rules for PHP Variables

  • A variable starts with the $ sign, followed by the name of the variable.
  • A variable name must start with a letter or the underscore character _.
  • A variable name cannot start with a number.
  • Variable names are case-sensitive ($age and $AGE are two different variables).
  • PHP is a loosely typed language, but PHP 8+ supports strict type declarations.

Variable Types in PHP

PHP supports 8 primitive data types:

Data Type Description Example
String Sequence of characters \$name = "Alice";
Integer Non-decimal whole number \$age = 28;
Float Number with a decimal point \$price = 19.99;
Boolean True or False \$isEnrolled = true;
Array Collection of values \$skills = ["PHP", "Laravel"];
Object Instance of a class \$user = new User();
NULL Variable with no value \$discount = null;

Practice Exercises

Exercise 1: Create and Output a PHP Variable

Easy

Declare a variable named $course and assign the string "Laravel 13" to it, then use echo to print it.

Starter Code:
<?php
// Declare your variable below:

💡 Hint: Remember variable names in PHP start with a dollar sign $ and strings are enclosed in quotes.
Solution:
<?php
$course = "Laravel 13";
echo $course;