PHP Variables
Variables are containers that are used to store different types of data. The variables can store character values, numeric values, memory addresses, and strings. PHP has its own way of declaring variables and storing data in it.
Syntax of Creating (Declaring) PHP Variables:
Any variables declared in PHP must begin with a dollar sign ($), followed by the variable name.
Syntax:
$variable_name=value;
Example
<?php
$txt = "Hello Vaidikalayans!";
$x = 5;
$y = 10.5;
echo $txt."\n";
echo $x."\n";
echo $y."\n";
?>
Rules for declaring PHP variable
There are a few rules, that need to be followed and facts that need to be kept in mind while dealing with variables in PHP:
- A variable starts with the $ sign, followed by the name of the variable.
- PHP is a loosely typed language, so we do not need to declare the data types of the variables. It automatically analyzes the values.
- A variable name must start with a letter or the underscore character.
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
- Variable names are case-sensitive ($age and $AGE are two different variables).
Examples 1: Case Sensitive
Check - Case Sensitive
<?php
$age=10;
echo $age."\n";
echo $AGE."\n";
?>
Examples 2: Valid Rules
Check - Valid Rules
<?php
$a=10;
$_=20;
echo $a."\n";
echo $_."\n";
?>
Example 3: Invalid Rules
Check - Invalid Rules
<?php
$5a=10;
$*b=20;
?>