Using Variables in PHP

A variable is simply a container that holds a certain value. Variables get their name because that certain value can change throughout the execution of the script. It's this ability to contain changing values that make variables so useful.

For example, consider the following simple PHP script.
     echo 2+2;

As you might imagine, this code outputs the number 4 when it's run. This is all well and good; however, if you wanted to print the value of, say, 5 + 6 instead, you'd have to write another PHP script, as follows:
      echo 5 + 6;

This is where variables come into play. By using variables instead of numbers in your script, you make the script much more useful and flexible:
      echo $x +$y;

Naming Variables

A variable consists of two parts: the variable's name and the variable's value. Because you'll be using vaiiables in your code frequently, it's best to give your variables names you can understand and remember. Like other programming languages, PHP has certain rules you must follow when naming your variables: -

  • Variable names begin with a dollar sign ($)
  • The first character after the dollar sign must be a letter or an underscore
  • The remaining characters in the name may be letters, numbers, or underscores without a fixed limit

Variable names are case-sensitive ($variable and $VARIABLE are two distinct variables), soit's worth sticking to one variable naming method - for example, always using lowercase - to avoid mistakes. It's also worth pointing out that variable names longer than 30 characters are somewhat impractical.

Here are some examples of PHP variable names;

$my_first_variable
$anotherVariable
$x
$_123

Creating Variables

Creating a variable in PHP is known as declaring it. Declaring a variable is as simple as using its name in your script:

$my_first_variable;

Here's an example of declaring and initializing a variable:
$my_first_variable=3;

Data Types

All data stored in PHP variables fall into one of eight basic categories, known as data types. A variable's data type determines what operations can be stored out on the variable's data, as well as the amount of memory needed to hold the data.

PHP supports four scalar data types. Scalar data means data that conrains only a single value.
Here's a list of them,including examples:

Integer: A whole Number
Example: 27

Float: A floating-point Number
Example: 23.4
String: A series of characters
Example: "Hello, World!"