Variables in PHP - How to Create, Rules and Examples

Variables in PHP - How to Create, Rules and Examples

What is Variable in PHP

Variable is like a Jar or Container, which stores information.
Not only in PHP, for any programming language, to process any data, we need to store something in somewhere and then, we process that data in later.

You can think it like, to calculate the summation of two numbers, we can store the summation to a jar and name it result. Then anywhere of our application, we can use that result. And in programming language, this result is actually the Variable.

How to declare a Variable in PHP

Variable Name Formula: Dollar sign ($) + name of the variable.
Example: $name $age $userName $name1 $name2 $_is_available $avatar_url

Assign a value to variable:

After getting the idea of a variable name, let’s assign a value or store a value to variable.

$name = "Jhon Doe";
$age = 28;
$avatar_url = "jhondoe@example.com";
$product_price = 1,200.50
$_is_available = true;

Summation value store example with variable:

$number1 = 20;
$number2 = 30;

$summation = $number1 + $number2;

Rules to Create a Variable name in PHP

  1. Variable name is case sensitive - $age and $AGE is not same variable.
  2. Variable starts with letter(a, b, … z) or underscore(_) eg: $name, $_age
  3. After first letter or underscore, then any letter, number or underscore
  4. eg: $user, $user1, $age, $user1_age, $user2_age
  5. Variable name should be meaningful (Not rule, but a very good convention) Like: $user_n is not good for a variable name for user name, we should rather name that like $user_name or $userName.

Invalid Variable Name Example in PHP

  1. $123 is not a valid variable - Variable should start with a-z or A-Z or with underscore. But here starts with Number.
  2. $ age is not a valid variable - Cause, after the $ sign, there is a space( ). It should not be a variable.
  3. $name 1 is not a valid variable but $name1 is - Inside variable name, there should not be any space.

Example of Some Valid Variable Name in PHP

  1. $name
  2. $age
  3. $userName
  4. $name1
  5. $name2
  6. $_is_available
  7. $avatar_url
  8. $NAME
  9. $USER_ADDRESS

Previous
Run our First PHP Program
Next
Data Types in PHP - Variable Types in PHP