Skip to content

PHP Tutorial Variables and Constants

PHP Variables

Lesson 21 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Think of a variable as a labelled box. You put a value inside the box and give the box a name. Later you use the name to get the value back.

index.php
PHP
<?php
$city = "Jaipur";
$population = 3000000;

echo $city;
echo "\n";
echo $population;
Output
OUTPUT
Jaipur
3000000

How to create a variable

A PHP variable has three parts:

  1. The dollar sign $ at the start.
  2. A name, such as city.
  3. A value, given with the = sign.

There is no keyword like let or var. You create a variable simply by giving it a value for the first time.

index.php
PHP
<?php
$price = 250;

PHP works out the type for you

You do not declare that $price is a number. PHP looks at the value and decides. That is called dynamic typing.

index.php
PHP
<?php
$value = 10;       // a number
$value = "ten";    // now a string
echo $value;
Output
OUTPUT
ten

This is flexible, but it can also hide bugs. Later in the course you will learn type declarations that make your code safer.

Using variables in text

Put a variable inside double quotes and PHP replaces it with its value.

index.php
PHP
<?php
$name = "Neha";
echo "Hello, $name!";
Output
OUTPUT
Hello, Neha!

Why we use variables

Without variables you would repeat the same value in many places. With a variable, you write it once and change it in one spot.

index.php
PHP
<?php
$siteName = "Code Corner";

echo "Welcome to $siteName\n";
echo "Thanks for visiting $siteName";
Output
OUTPUT
Welcome to Code Corner
Thanks for visiting Code Corner

Exercise: a profile card

Create variables for a person’s name, city and age. Print a sentence like Asha is 24 and lives in Kochi.

Show a possible solution
index.php
PHP
<?php
$name = "Asha";
$age = 24;
$city = "Kochi";

echo "$name is $age and lives in $city.";
Output
OUTPUT
Asha is 24 and lives in Kochi.