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.

Php Variable – Questions and Answers

Q 1: What is a variable in PHP?

Ans: A variable is used to store data values.

Q 2: How to declare a variable in PHP?

Ans: Variables start with $ followed by the variable name.

Q 3: Are PHP variables typed?

Ans: No, PHP is dynamically typed.

Q 4: Can variable names start with a number?

Ans: No.

Q 5: What is variable scope in PHP?

Ans: Scope defines where a variable can be accessed.

Php Variable – Objective Questions (MCQs)

Q1. PHP variables start with which symbol?






Q2. Which variable name is valid in PHP?






Q3. Variable names in PHP are ______.






Q4. PHP variables can store ______ types of values.






Q5. Which is correct way to assign a value to a variable?






Related Php Variable Topics