Variables in PHP



Variables are nothing but identifiers which point to a memory location in which data is stored. Variable in PHP are quite different from compiled languages such as C and Java. This is because PHP variable are weakly typed. This means that when a PHP variable is being defined their data type is not declared prior their use. A PHP variable takes its data type from the user defined value that is being stored in it. As a result, a PHP variable can change its type as often as needed.

A PHP Variable must be named/declared string with the $character followed by a letter. The rest of the variable name can consist of a mix both alphabets and numbers.
·        $var
·        $name2
·        $address_22


The _ (underscore) character can also be used in variable. It is used as a replacement for space. Space is a character that cannot be used when naming a PHP variable.

The characters are not allowed in a variable name:
* (Asterix)
+ (Plus)
# (Hash)
@ (At the rate)
- (Minus)
& (Ampersand)
£ (Pound)

There is no limit on the size of variable in PHP.

Once a variable is named, it is empty until assigned a value. To assign a value to variable:
$name = ‘Cyber Teak’;
Everything inside the single quotes will be assigned to the variable named name. The named variable is on the left side of = (assignment operator) and the value to be held by the variable is on its right.
Similarly numeric values can be assign.
$code = 2020;
Here $code is assigned a value of 2020. The only difference is that the value 2020 is passed without quotation marks.
Different types of values can be assigned to variables. Integer and String types have already demonstrated.

Example:1
<?php            $Name = “CyberTeak.com”;            echo $name;
?> 
Explanation: In the example a variable named $Name is declare. The value CyberTeak.com has been assigned but while accessing the value held by the variable, the variable name is in lowercase. This example when run displays the error on the screen:

Notice: Undefined variable : name on line 3

Example: 2

<?php
            $Category = “Educational ”;
            echo $Category;
$Address_code = 123456;
echo $Address_code;
?>

Post a Comment

0 Comments