PHP | Variable
A variable is a user define keyword which is used to store value like string, number, and array. Once a variable is defined then we can use it one or more than one time in our script.
A PHP variable starts with the $ sign symbol. If we miss-use of the $ sign then it will throw an error. The correct way to declare a PHP variable:
$variable_name = value
Let's see an example:
<?php $var = "Hello PHP"; $var1 = 10; $var_txt = 5 + 6; $var_arr = array('Ram', 'Shyam', 'Remesh'); ?>
Above example contions 4 variable having diffrent value. $var variable storing a string 'Hello PHP', $var1 variable storing number 10, $var_txt variable storing sum of two number 5 and 10, and $var_arr variable storing array of person name.
PHP is a loosely typed language, therefore the variable is declared automatically when we use it. We need not declare a variable before using it as we define it in other programming languages (Java, C, C++, etc).
In the above example, we see that we do not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type for us, depending on its value.
PHP variable naming convension
- A variable can only start with a letter or an underscore "_".
- Only alpha-numeric characters and underscore is allowed
- If a variable name is more than one word, it should be separated by an underscore (i.e. $my_var) or by capitalization($myVar).