PHP Variables

A variable is a storage area. You can think about variables like temporary boxes in a computer’s memory to store data. PHP uses Variable to store different type of Data.

For example, if we want to store our name in a PHP script and then see it on the web page, we can use a PHP variable to store our name.

You need two steps to work with variables:

  1. variable declaration
  2. variable call

STEP 1. Variable declaration:

To declare a variable you have to follow this syntax:

$varName = value;

PLEASE NOTE:

  • variables in PHP start with a dollar sign ($)
  • variables’ names are case sensitive
  • you can use alphanumeric characters and underscores (no spaces)
  • the first character of a string name can be a letter or an underscore (no numbers)
  • you can assign a value to a variable using the assignment operator (=)
  • you cannot name a variable $this
  • if the value is a piece of text (a string) you have to wrap the value in between quotation marks
  • if the name of the variable contains more than one word, please use lower camel case notation (e.g. $thisIsMyName or $varNameHere)

STEP 2. Variable usage:

To refer to the value of a variable, just write its name.

PLEASE NOTE:

  • If you echo a variable name between double quotation marks (“$myNAme”) you will output the value of that variable (e.g. john)
  • If you echo a variable name between single quotation marks (‘$myNAme’) you will output the name of that variable (e.g. $myName)

Variables declaration and datatype

Unlike other programming languages, PHP is a loosely typed language. For this reason you do not have to declare a type while declaring a new variable. While variables do not have specific types, PHP still maintains the concept of a type.

The principal types in PHP are:

  • Integer (e.g. 4)
  • Float (e.g. 2.3)
  • String (e.g. “dog”)
  • Boolean (true or false)

You can use isset() to determine whether a variable has been set and is not null.

The above example declares a variable $myVar, then displays it only if it has been correctly set.

Click here to read more about IF statements.

 

Long multiline strings can be stored into variables using HEREDOC syntax:

You can concatenate strings using the . operator:

Of course you can use variables to store and operate with Numbers:

 

Click here to read about data types.