Page Stats
Visitor: 533
PHP Variable
A Variable is a small temporary memory area use to store value entered by the user, the value may be decimal number, non-decimal number, text, date, etc. In other words, variables are the "containers" for storing information.
Rules to declare a PHP variable are:
- A variable must starts with the '$' (dollar) sign, followed by the variable name.
- A variable name can contain letters, numbers, and underscores.(A-Z, a-z, 0-9, and _ )
- A variable name must begin with a letter or the underscore character, it cannot begin with a number.
- A variable name cannot contain special characters.
- Variable names are case-sensitive ($age and $AGE are different variables).
PHP Data Types
Data types define the type of value entered by the user. PHP has a total of 8 data-types which we use to store variable:
- Integer Integer contain numeric value that can be positive or negative, but without a decimal point, e.g. $var = 1234;
- Double Double contain numeric as well as floating-point number, e.g. $num = 2.2888855;
- Boolean Boolean have only two possible values either true or false. e.g. $x = true; Boolean are often used in conditional testing.
- NULL NULL is a special data type that only has one value:NULL. e.g. $my_var = NULL;
- String The string is a collection of characters, e.g. $str = "This is a string". A string can be any text inside quotes. You can use single or double quotes to represent strings.
- Array An array stores multiple values in one single variable. Like $colors = array("Red","Green","Blue");
- Object Object are instances of a class, which can package up both kinds of values and functions that are specific to the class.
- Resource Resource are the special variables that hold references to resources external to PHP (such as database connections).
Example 1: Some Valid Variable Declaration:
$txt = "Programming is Fun!"; //variable with string value $a = 5; // variable with integer value $b = 10.5; //variable with float value $_city = "Delhi"; //variable with underscore character $marks2 = 50; //variable name contain number
Example 2: Some In-Valid Variable Declaration:
$2marks = 50; //variable name cannot contain number. $@city = "Delhi"; //variable name cannot contain special characters like @. $area of circle = 50.5; //variable name cannot contain spaces.
A variable can have a short name (like a, b or any alphabet) or a more descriptive name (like name, age, areaofcircle, total_marks etc).