Screen Printing

TUTORIALS » PHP / MySQL » PHP essentials (guided tutorials)

Variables in PHP

Page 1 of 2


You are in page:
» 1. Introduction
Variables are one of the keystones of programming. Putting it simply, variables are keywords or letters that serve as "memories" to store numbers, strings (text), or even tables of data.

The basic syntax to define a variable is by writing a dollar sign ($) followed by the desired name of the variable (without spaces), the equal sign, and the desired value for the variable.

Example:
<?php
 $myCountry = 'France';
 $myAddress = '782 Rue de la Fayette, Paris'; 
 //Don't send me postcards, this is not my real address!!
 $myAge = 74;
?>
Note: My variables here are colored in red and their values in blue.

Remember, in PHP all strings must be written between quotation marks. On the other hand, when you store a number in a variable, it is not necessary to put it between quotation marks (although you can do it if you want to).

Operations with variables

Once you have defined a variable and its value, you can retrieve that value, print it, change it, make calculations with it, store the result in another variable, etc.

Example:
<?php
 $a = 7;
 $b = 10;
 $c = $a + $b; //The value of $c will be 17
 $d = $a * $b; //The value of $d will be 70
 $e = ($d - $b) + 3; //The value of $e will be 63
?>

Replacing variables

You can replace the value of a variable with a new value.

Example:
<?php
 $blah = 5;
 $blah = $blah * 5; //The new value for $blah is 25
?>

Concatenation of variables

You can also join the value of two or more variables in a single string. This textual combination of strings is called concatenation.

Example:
<?php
 $name = "John";
 $age = 45;
 $introduction = "Hello, my name is $name and I am $age years old";
 //The value of $introduction will be: 
 //   Hello, my name is John and I am 45 years old.
?>

In the next tutorial you will learn more about concatenation of strings, and the comparison of single quotes and double quotes.

Now go to the next page of this tutorial for a short practice on the use of variables.

More pages of this tutorial → Variables in PHP  12>

Comments & Questions