Skip to content
← Back to Community
PHP tutorial No. 2: Variables
Profile icon

PHP tutorial No. 2: Variables

Variables section in the PHP language reference

Types section in the PHP language reference

Variables are named locations in a program's memory that can store values. Values have a data type, though these do not need to be stated when variables are declared (like in some languages like C++ e.g. int age; double height).

The allowable types are:

  • String
  • Integer
  • Float - sometimes called doubles
  • Boolean - true (TRUE) or false (FALSE)
  • Array
  • Object
  • NULL
  • Resource

Rules for variable naming

  • Names should describe the value they are storing
  • Names start with a $ symbol followed by the name of the variable.
  • A variable name must start with a letter or the underscore character.
  • A name cannot start with a number.
  • It can only contain alpha-numeric characters and underscores e.g. a-z,A-Z, 0-9, and _
  • Names are case-sensitive e.g. $Banana and $banana are two different variables.

The more common data types

PHP will work out the type of a variable when a value is assigned to it. For example the following variables store an integer, float, string and Boolean respectively.

$num_apples = 5; $height = 1.83; $name = "Albert Einstein"; $coding_is_cool = true;

Numeric variables can be added, subtracted etc. The operators are the same as those used in C, C++, JavaScript and other languages based on C.

The following code converts a temperature from celcius to fahrenheit.

$celcius = 100; $fahrenheit = $celcius * 9 / 5 + 32;

Note that statements have to have a semi-colon at the end of each line.

Below are some other examples of using variables.

// Note: single line comments start with double slashes // Strings are quoted text - single or double quotes can be used but they must match $first_name = "Albert"; $last_name = 'Einstein'; // Use the concatenation operator (a dot) to "join" single spaces into the $full_name string $full_name = $first_name . " " . $last_name; // Resultant string is: "Albert Einstein"

Variables can be embedded in a string that is double quoted. The value of the variable is substituted in the string when it is processed by the PHP parser e.g.

echo "The most famous scientist in the world is $full_name"; // Resultant string is: "The most famous scientist in the world is Albert Einstein"

If single quotes are used to 'quote' a string that contains variables, the variable names will be displayed rather than the values they hold.

$fav_animal = "Sloth"; echo 'My favourite animal is a $fav_animal'; // Resultant string is: "My favourite animal is a $fav_animal"

The code below shows how to use a variable storing a Boolean. It also shows how to use the if/else construct. Note how it is the same as that used in the C++ and JavaScript languages:

$logged_in = false; if (logged_in == true) { echo "Hi, you are logged in"; } else { echo "Oh dear, you are not logged in!!"; }


Single and multi-dimensional arrays

Arrays are powerful data structures that usually store multiple values that are related in some way. For example the following $animals array stores the names of animals.

// A one dimensional array $animals = ["horse", "pig", "monkey", "sheep", "elephant"];

Values can be accessed by using the index values of array elements. These start at 0 for the first element, so to display the second element ("pig") the following code will be used. Note the use of the concatenation character to build-up the string.

echo "<p>" . $animals[1] . "</p>"; // Resultant string is: "<p>pig</p>"

Replace pig with giraffe

$animals[1] = "giraffe"; echo "<p>" . $animals[1] . "</p>"; // Resultant string is: "<p>giraffe</p>"

Add a new animal. Note the use of the empty square brackets after the array name

$animals[] = "walrus";

Arrays can be muti-dimensional. This means arrays within other arrays. Below is an example. The arrays inside the main array hold information on pets - their: name, age (in years), and favourite food.

$pets = [["Felix", 2, "jelly meat"], ["Fido", 5, "dog biscuits"], ["Fishy", 3, "food flakes"]]; // Display Fido's name, age and favourite food echo "<h1>" . $pets[1][0] . " is " . $pets[1][1] . " years old and there favourite food is " . $pets[1][2] . "</h1>";

Note how the concatenation operator (the dot) has to be used to "stitch" the array values into the string. Unlike variables that hold the number, string and boolean data types, interpolating array values in a double quoted string will not cause the corresponding values to be substituted. So the code below will NOT work.

echo "<h1>$pets[1][0] is $pets[1][1] years old and there favourite food is $pets[1][2]</h1>"; // Displays <h1>$pets[1][0] is $pets[1][1] years old and there favourite food is $pets[1][2]</h1>

Associative arrays

Associative arrays are often a more useful type of an array. Values called keys are pair a value. To get or set a value the key, which is often a string, is used in the square brackets after the array name, rather than an index number. The following example shows an example and how to get and set a value. Note the person's name is used as the key and their age is the associated value.

$names_and_ages = ["ben" => 25, "mary" => 20, "phillis" => 23]; // Display mary's age echo "<p>Mary's age is: " . $names_and_ages["mary"] . "</p>"; // Resultant string is: "<p>Mary's age is 20</p>" // Change Mary's age to 28 $names_and_ages["mary"] = 28; echo "<p>Mary is now older. She is " . $names_and_ages["mary"] . " years old</p>"; // Resultant string is: "<p>Mary is now older. She is 28 years old</p>" // Add another person and their details to the array $names_and_ages["anne"] = 26;

Arrays can be more complex. The following array uses a mix of one dimensional and associative arrays to store information on people.

$people = [ ["name" => "John Smith", "address" => "1 pudding Lane", "age" => 21], ["name" => "Mary Brown", "address" => "2 pudding Lane", "age" => 26], ["name" => "Anne White", "address" => "10 pudding Lane", "age" => 22] ];

The values in the array can be displayed as a series of lists using a for loop, like so:

// The count function returns the number of items in the array for ($counter = 0; $counter < count($people); $counter += 1) { echo "<ul>"; echo "<li>Name: " . $people[$counter]["name"] . "</li>"; echo "<li>Address: " . $people[$counter]["address"] . "</li>"; echo "<li>Age: " . $people[$counter]["age"] . "</li>"; echo "</ul>"; }

Here is a link to a program that shows the above code in action: Mixed arrays example

Previous tutorial: Introduction to PHP

Next tutorial: Decisions

Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon