How to declare Variables in PHP

In programming, variable is a storage location where data will be stored. In php we declared variable using $(Dollar) symbol.

Variable Declaration Example

$x=3;

Note:-var_data is a variable name. It can be anything or any datatype like string, number, boolean etc.

Assign value to the variable

$name="techaltum"; $pin=201301;

You can also declare and assign value in single line.

Assign value to variable

Following is the example where I used variable and assign a value

 
<?php
$data;
$data="isha Malhotra";
echo "$data";
?>

		

When I execute this program it will show the following output:-


Variable declaration in php

		Figure 1
		

Variable declaration and definition is must. Suppose if I only declared a variable without assigning the value then it will produce the error.

For Example:-

 
<?php
$data;
echo "$data";
?>
		

In this code I only declare the variable but didn't assign any value. The output of this code as follows:-

			
variable declaration and assignment

		Figure 2
	
		

As you can see that it is showing error that it is undefined variable. So it is must that if we declare any variable then before using this variable we must have to assign value in it?

If we use single quotation with echo and try to print then it will print text instead of print the value of variable.

			
<?php
$data;
$data="Isha Malhotra";
echo '$data';
?>


		

The output of this code as follows:-

			
echo command in php

		Figure 3
	
		

In this article I'll described the basic part of variable in php.