Web Statistics

PHP Variables

Assigning data to a variable

Variable Rules

A variable is simply a data item that may take on more than one value during the runtime of a program. There! That was the Google definition incase you were looking.

Before we dive into variables we need to understand what values can be set to a variable. These values include, but not limited to:

  • Booleans
  • Integers
  • Floats
  • Strings
  • Arrays
  • Objects
  • Resources
  • NULL

Variable Rule #1

Variables are represented by a dollar sign followed by the name of the variable. (example: $variable_name)

Variable Rule #2

The variable name is case-sensitive.

Variable Rule #3

A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Variable Rule #4

The variable $this is a special variable that can't be assigned.

Assign Variables

The following is an example of assigning basic values to variables.

<?php
//Null
$null_variable = null;

//Booleans
$boolean_true = true;
$boolean_false = false;

//Integers
$integer1 = 1;
$integer2 = 2;
$integer3 = 3;

//Floats
$float1 = 9.99;
$float2 = 3.1415926535897932384626433832795028841971693993;

//Strings
$string1 = "PHP is Awesome";
$string2 = 'Strings can be enclosed with single or double quotes';

//Arrays
$array1 = array('red','green','blue');
$array2 = array(
	'red'=>1,
	'green'=>2,
	'blue'=>3
);
?>

I think that you can see the pattern. Try not to focus on the differences such as:

  • Why can strings be enclosed with single or double quotes?
  • Why do the two array examples look so different?

Focus more on the format of how variables are assigned. The variable starts with a dollar sign ("$"), and the the value setter is initiated by the equal sign ("=").

Predefined Variables

Predefined variables are an important feature in PHP. There is a lot to cover here so I will defer to the knowledge base at www.php.net. Check out the resources on the section that covers the predefined variables.

Up Next

A Variable of a Variable is a Variable.