An Introduction to PHP Variables

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Commenting PHP CodeUnderstanding PHP Variable Types


Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99


A large part of writing scripts and for that matter programming in general, involves the handling and manipulation of data. Data can take many forms, ranging from single characters, words and sentences to integers, floating point numbers and true and false values. In object oriented environments such as PHP, data can also take the form of an object, a self contained module which is capable of encapsulating any number of data values of numerous different types.

When working with data values in PHP, we need some convenient way to store these values so that we can easily access them and make reference to them whenever necessary. This is where PHP variables come in.

It is often useful to think of variables as computer memory locations where data is to be stored. When declaring a variable in PHP it is assigned a name that can be used to reference it in other locations in the PHP script. The value of the variable can be accessed, the value can be changed, and the type of variable can be altered all by referencing the name assigned at variable creation time.


Contents


Naming and Creating a Variable in PHP

Before learning how to declare a variable in PHP it is first important to understand some rules about variable names (also known as variable naming conventions). All PHP variable names must be pre-fixed with a $. It is this prefix which informs the PHP pre-processor that it is dealing with a variable. The first character of the name must be either a letter or an underscore (_). The remaining characters must comprise only of letters, numbers or underscores. All other characters are deemed to be invalid for use in a variable name.

Let's look at some valid and invalid PHP variable names:


$_myName // valid
$myName  // valid
$__myvar // valid
$myVar21 // valid
$_1Big   // invalid - underscore must be followed by a letter
$1Big    // invalid - must begin with a letter or underscore
$_er-t   // invalid contains non alphanumeric character (-)

Variable names in PHP are case-sensitive. This means that PHP considers $_myVariable to be a completely different variable to one that is named ''$_myvariable.

Assigning a Value to a PHP Variable

Values are assigned to variables using the PHP assignment operator. The assignment operator is represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the left of the expression, followed by the assignment operator. The value to be assigned is then placed to the right of the assignment operator. Finally the line, as with all PHP code statements, is terminated with a semi-colon (;).

Let's begin by assigning the word "Circle" to a variable named myShape:

$myShape = "Circle";

We have now declared a variable with the name myShape and assigned a string value to it of "Circe". We can similarly declare a variable to contain an integer value:

$numberOfShapes =  6;

The above assignment creates a variable named numberOfShapes and assigns it a numeric value of 6. Once a variable has been created, the value assigned to that variable can be changed at any time using the same assignment operator approach:

<?php

$numberOfShapes =  6; // Set initial values
$myShape = "Circle"; 

$numberOfShapes =  7; // Change the initial values to new values
$myShape = "Square"; 

?>

Accessing PHP Variable Values

Now that we have learned how to create a variable and assign an initial value to it we now need to look at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple as referencing the name it was given when it was created.

For example, if we want to display the value which we assigned to our numberOfShapes variable we can simply reference it in our echo command:

<?php
echo "The number of shapes is $numberOfShapes.";
?>

This will cause the following output to appear in the browser:

The number of shapes is 6.

Similarly we can display the value of the myShape variable:

<?php
echo "$myShape is the value of the current shape.";
?>

The examples we have used for accessing variable values are straightforward because we have always had a space character after the variable name. The question arises as to what should be done if we need to put other characters immediately after the variable name. For example:

<?php
echo "The Circle is the $numberOfShapesth shape";
?>

What we are looking for in this scenario is output as follows:

The Circle is the 6th shape.

Unfortunately PHP will see the th on the end of the $numberOfShapes variable name as being part of the name. It will then try to output the value of a variable called $numberOfShapesth, which does not exist. This results in nothing being displayed for this variable:

The Circle is the shape.

Fortunately we can get around this issue by placing braces ({ and }) around the variable name to distinguish the name from any other trailing characters:

<?php
echo "The Circle is the ${numberOfShapes}th shape";
?>

To give us the desired output:

The Circle is the 6th shape.

Changing the Type of a PHP Variable

As we mentioned at the beginning of this chapter, PHP supports a number of different variable types (specifically integer, float, boolean, array, object, resource and string). We will look at these types in detail in the next chapter (Understanding PHP Variable Types). First we are going to look at changing the type of a variable after it has been created.

PHP is what is termed a loosely typed language. This contrasts with programming languages such as Java which are strongly typed languages. The rules of a strongly typed language dictate that once a variable has been declared as a particular type, its type cannot later be changed. In Java, for example, you cannot assign a floating point number to a variable that was initially declared as being a string.

Loosely typed languages such as PHP (and JavaScript), on the other hand, allow the variable type to be changed at any point in the life of the variable simply by assigning a value of a different type to it. For example, we can create a variable, assign it an integer value and later change it to a string type by assigning a string to it:

<?php

$myNumber = 6; // variable is of integer type

$myNumber = "six"; // variable has now changed to string type

?>

The process of dynamically changing the type of a variable is known as automatic type conversion.

Checking Whether a Variable is Set

When working with variables it is often necessary to ascertain whether a variable actually has a value associated with it or not at any particular point in a script. A mechanism is provided with PHP to provide this ability through the isset() function. To test whether a variable has a value set simply call the isset() function passing through the name of the variable as an argument (see PHP Functions for details of passing through arguments to functions). The following code example tests to see if a variable has a value or not and displays a message accordingly:

<?php

$myVariable = "hello";

if (isset($myVariable))
{
    echo "It is set.";
} 
else
{
    echo "It is not set.";
}
?>

If you are unfamiliar with using if statements in programming and scripting languages don't worry - we will cover them in the PHP Flow Control and Looping chapter.


Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99