PHP: Variables

Variables in PHP are used for storing values like numbers (integer and float), characters, strings/texts, null, boolean (true/false), and also derived data types like arrays and objects. Unlike variables in languages like PASCAL and C, PHP variables do not need to be declared of their type before assigning values to them.

Variables in PHP start with a $ (dollar) sign followed by the name of the variable, which begins either with an alphabet (a-z,A-Z) or with an underscore (_). Variable names may contain alphabets (a-z,A-Z), numbers (0-9) and underscores (_) but they cannot start with a number and cannot contain any other special characters beside the underscore (_). Below are examples of some valid PHP variable names

				
					$e; // valid
					$name; // valid
					$_base; // valid;
				
			

and some invalid variable names

				
					$1stPrime; // invalid; starts with a number
					$di@meter; // invalid; contains a special character '@'
				
			

PHP Variables are Case-Sensitive

Variable names in PHP are case-sensitive. Which means, $e is not the same as $E, and $firstName is not the same as $FirstName.

PHP Variable Variables

In PHP, a variable can be named with the value assigned to another variable. They are known as variable variables or dynamic variable names. Below we construct a variable named pi with the value assigned to another variable $irrational, and assign it the value 3.141

					
						$irrational = 'pi';
						$$irrational = 3.141; // new variable named with the value of $irrational
						echo $pi; // prints 3.141
					
				

Since $irrational equals pi, substituting the value of $irrational in $$irrational gives $pi. That's why the statement echo $pi; prints out 3.141.