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
¶How to declare a Variable in PHP
Variable Name Formula: Dollar sign ($) + name of the variable.
¶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 = "email@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
- Variable name is case sensitive -
$AGEis not same variable.
- Variable starts with letter(a, b, … z) or underscore(_) eg:
- After first letter or underscore, then any letter, number or underscore
- eg: $user, $user1, $age, $user1_age, $user2_age
- Variable name should be meaningful (Not rule, but a very good convention) Like:
$user_nis not good for a variable name for user name, we should rather name that like
¶Invalid Variable Name Example in PHP
$123is not a valid variable - Variable should start with a-z or A-Z or with underscore. But here starts with Number.
$ ageis not a valid variable - Cause, after the
$sign, there is a space(
$name 1is not a valid variable but
$name1is - Inside variable name, there should not be any space.
¶Example of Some Valid Variable Name in PHP