PHP Variables

PHP Variables

A variable is declared in PHP by putting a $ sign before the variable name. Here are some key facts to remember regarding variables:

We don't need to define the data types of the variables because PHP is a weakly typed language. It examines the values and converts them to the right data type automatically.

A variable can be reused throughout the code after it has been declared.

To assign a value to a variable, use the assignment operator (=).

The following is the syntax for declaring a variable in PHP:

$variablename=value; PHP variable declaration rules:

  • A variable must begin with a dollar sign ($) and end with the variable name.
  • Only alpha-numeric and underscore characters (A-z, 0-9, _) are allowed.
  • The name of a variable must begin with a letter or the underscore (_) character.
  • There can't be any spaces in the name of a PHP variable.
  • It's important to remember that the variable name cannot begin with a number or a special symbol.
  • Because PHP variables are case-sensitive, $name and $NAME are processed separately.

PHP Variable: Declaring string, integer, and float

Let's see the example to store string, integer, and float values in PHP variables.

File: variable1.php

<?php $str="knowledge 2life string"; $x=100; $y=40.6; echo "string is: $str <br/>"; echo "integer is: $x <br/>"; echo "float is: $y <br/>"; ?>


string is: knowledge 2life string integer is: 100 float is: 40.6

PHP Variable: Sum of two variables

File: variable2.php

<?php $x=6; $y=8; $z=$x+$y; echo $z; ?>



PHP Variable: case sensitive

Variable names in PHP are case-sensitive. As a result, the variable name "colour" differs from Color, COLOR, COLor, etc.

File: variable3.php

<?php $color="blue"; echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR . "<br>"; ?>


My car is blue Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4 My house is Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5 My boat is

PHP Variable: Rules

PHP variables can only begin with a letter or an underscore.

Numbers and special symbols cannot be used to begin a PHP variable..

File: variablevalid.php

<?php $a="knowledge 2life";//letter (valid) $_b="knowledge 2life";//underscore (valid) echo "$a <br/> $_b"; ?>


knowledge 2life knowledge 2life

File: variableinvalid.php

<?php $4c="hello";//number (invalid) $*d="hello";//special symbol (invalid) echo "$4c <br/> $*d"; ?>


Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE) or '$' in C:\wamp\www\variableinvalid.php on line 2