A variable is used to store data and allows different operations to perform.

PHP is a loosely typed or dynamic language. Hence variable need not to be declared before using. PHP allows to use different data type like number, decimal, string, array, object etc.

Syntax

$variable_name = value;

Example

<?php
// Declaring variables
$txt = "Hello World!";
$number = 10;
?>

In above example, two variable $txt and $number is declared with different values

VariableValueValue type
$txt“Hello World!”Holds string value
$number10Holds integer value

Same variable with different values

<?php
// Declaring variables
$txt = "Hello World!";
echo $txt;
$txt = 20;
echo $txt;
?>

In above example, firstly $txt holds string and again it holds an integer value. Because PHP is loosely type language, it allows to use variable as per requirement. But it is not a good or recommended practice.

Output PHP variable value

PHP has many functions to output variable’s value, but echo is mostly used.

<?php
// Declaring variables
$txt = "Hello World!";
echo $txt;
$number = 10;
echo $number;
?>

Assign same value to Multiple variables

PHP allows to assign same value to more than one variables at once.

$a = $b = $c = $d = 40;

Above example $a, $b, $c, $d has same value 40.

Get Variable Data type

PHP has var_dump() function to get the type of data a variable is currently holding.

<?php

 $number = 20;
 var_dump($number);

 $txt = "PHP";
 var_dump($txt);

?>

var_dump() function does not need echo to output, use it directly to get the type of variable data.