Variables in PHP
Variables are used in a program to store some value or data which can be used later in the program.PHP is a loosely typed language.
1. No fixed data type to a variable
2. Variables can contain any value – number, string or reference
3. Arrays are special variables to hold multiple values
4. Variables are preceded with $
5. PHP is case sensitive. $x is different from $X
Syntax
Syntax of declaring a variable in PHP is given below:
<?php
$variablename=value;
?>
Example
<?php
$x=10; # integer assignment
$x="string here"; # string assignment
$x=10.25; # double/float assignment
$x=TRUE; # boolean Value
?>
No fixed size of memory : No need to declare a variable. Memory is allocated at the time of initialization. Unlimited memory. Memory grows and shrinks automatically.
<?php
$x="abc"; #3 character string
$x="this is a bigger string"; # a bigger string assigned
?>
Automatic type conversion
The type of the value is temporarily auto converted to type required in the current expression. String to numeric conversion results in a number, if the string is starting with a number. If the string is not starting with a number it results in 0.
<?php
$x="10";
echo $x+20; #prints 30 as $x is assumed as 10
?>
PHP Variables Scope
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. There are three different variable fields in PHP:
Local Variables: Variables declared within a function are called local variables for that function and have scope only in that particular function.
Global Variables: Variables declared outside a function are called global variables. These variables can be accessed directly outside a function.
Static Variables: It is the feature of PHP to delete the variable, once its execution is completed and the memory is freed.
<?php
$a = 5; // global scope
function myTest() {
$b = 5; // local scope
static $c = 0; //static scope
}
myTest();
?>
PHP Variable: Sum of two variables
#Source Code
<?php
$a=5;
$b=6;
$c=$a+$b;
echo $c;
?>
#Output
11