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.
<?php
$city = "Jaipur";
$population = 3000000;
echo $city;
echo "\n";
echo $population;
Jaipur
3000000
How to create a variable
A PHP variable has three parts:
- The dollar sign
$at the start. - A name, such as
city. - 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.
<?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.
<?php
$value = 10; // a number
$value = "ten"; // now a string
echo $value;
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.
<?php
$name = "Neha";
echo "Hello, $name!";
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.
<?php
$siteName = "Code Corner";
echo "Welcome to $siteName\n";
echo "Thanks for visiting $siteName";
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
<?php
$name = "Asha";
$age = 24;
$city = "Kochi";
echo "$name is $age and lives in $city.";
Asha is 24 and lives in Kochi.