Php Variable

Php variable is different from other programming languages like Java, .Net, c, c++, etc because PHP variable is weakly typed and you can change the datatype of the variable whenever you want. You can use PHP variable without prior declaration.
Php variable is introduced through the dollar($) sign.


<?php
$name='John';
?>

Display the varible value through echo or print

echo and print is used to display the value.

Example:-


<?php
$name='John';
echo $name;
?>

Try it Yourself

Output:- John

Example:-


<?php
$name='John';
print $name;
?>
Output:- John

Try it Yourself

Declare PHP variable

You can declare variables through the string, underscore, and numbers but the first character should not be a number.

Example:- Suppose, You declare variable through $name variable.


<?php
$name='John';
echo $name;
?>
Output:-John

Example:- Suppose, You declare variable which is start through underscore (_) through $_name variable.


<?php
$_name='John';
echo $_name;
?>
Output:-John

Example:- Suppose, You declare variable $1_name then it will show error when you echo this variable


<?php
$1_name='John'; 
echo $1_name;
?>
Ouput:-syntax error, unexpected ‘1’ (T_LNUMBER), expecting variable (T_VARIABLE)

Weakly Datatype

Php variable datatype is weakly datatype.

Example:- Suppose, you declare string value into name variable after that you defined numeric value into name variable then it will show last update value.


<?php
$name="John";
$name= 25;
echo $name
?>
Output:-25

Try it Yourself

Indirect Reference

PHP allows you to access a variable using indirect reference. There are no limits regarding the number of indirect references that you can use.


<?php
$car='TataNexon'; 
$TataNexon="This is developed by Tata Motors";
echo $$car;
?>
Output:- This is developed by Tata Motors

Try it Yourself

In the above example firstly execute $car variable and get the value TataNexon after that $TataNexon variable will execute and get the value This is developed by Tata Motors.