PHP Tutorial PHP Advanced PHP References

PHP - Variables



Variable is a given name to a reserved memory location. When a variable is created in the program, it reserves some space in the memory to store value(s) and the interpreter allocates memory for the given variable based on its datatype. Value(s) is stored in the variable by assigning different datatypes to it like number, string and sequences, etc.

Variable Declaration

PHP does not require to declare a variable or its data type. The data type of a variable is set when a value is assigned to it. To assign a value(s) to the variable, = operator is used.

All variables in PHP are denoted with a leading dollar sign $. The value and datatype of a variable is determined by its most recent assignment.

<?php
//store number in the variable 'x'
$x = 15;
echo "$x \n";

//store text in the variable 'y'
$y = "Hello";
echo "$y \n";
?>

The output of the above code will be:

15
Hello

In PHP, when a new value is assigned to the variable, the old value and its datatype will be overwritten by new value and its datatype.

<?php
//variable 'x' holds integer datatype with value 15
$x = 15;
echo "$x \n";

//Now, variable 'x' holds string datatype with value 'Hello'
$x = "Hello";
echo "$x \n";
?>

The output of the above code will be:

15
Hello

Variable Name

There are some reserved keywords in PHP which cannot be used as variable name. Along with this, rules for creating PHP variable name are listed below:

  • It must start with a letter or the underscore character
  • It cannot start with a number.
  • It can only contains alpha-numeric characters and underscores (A-Z, a-z, 0-9, and _ ).

Please note that PHP is a case-sensitive language. Hence, variables in PHP are also case-sensitive.

Print Variable

There are two ways of displaying variables value in output: using echo and print statement.

The echo statement can be used with or without parenthesis - echo and echo(). In the example below, it is used to display variables in two ways.

<?php
$x = 15;
$y = 10;  

echo "Value of x is ".$x." and Value of y is ".$y.".\n";

//another way to display the same
echo "Value of x is $x and Value of y is $y.\n";
?>

The output of the above code will be:

Value of x is 15 and Value of y is 10.
Value of x is 15 and Value of y is 10.

Similarly, the print statement can also be used with or without parenthesis - print and print(). In the example below, it is used to display variables in two ways.

<?php
$x = 15;
$y = 10;  

print "Value of x is ".$x." and Value of y is ".$y.".\n";

//another way to display the same
print "Value of x is $x and Value of y is $y.\n";
?>

The output of the above code will be:

Value of x is 15 and Value of y is 10.
Value of x is 15 and Value of y is 10.