PHP Tutorial – Variables

In this PHP programming language tutorial we will look at variables. A variable is used to store information or values in, like text-strings, numbers or arrays. As long as you don’t remove the value in a variable then you can use the variable (thus the value) over and over again.

PHP Variable Declaration

All variables in PHP begin with the $ sign. A common mistake of new PHP programmers is to forget the $ sign before a variable, so don’t forget it!

Let’s look at a variable declaration in PHP:


<?php
     $my_variable = 20;
     $my_variable2 = “Hello World”;
?>

First we declare a variable $my_variable with the value of 20. The second variable declaration we use a string “Hello World”.

Note: in both cases we end with a semicolon. The semicolon marks the end of the statement. If you forget a semicolon you will get an unexpected result or the program will do nothing. So don’t forget to end a statements with a semicolon!

Note 2: for people that have written programs in other language, such as C/C++ for instance, you don’t have to determine the data type of the variable (example in C Language: int my_var = 20; .) The PHP language is a loosely typed language, which means that PHP automatically converts the variable to the correct data type, depending on its value. The C/C++ languages are strongly typed programming languages.

Variable Rules

You have to follow some rules when naming a variable:

  • A variable name cannot contain spaces.
  • A variable name must start with a letter or an underscore ( _ )
  • A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )

That’s all for this PHP tutorial on variables in PHP.

This entry was posted in PHP Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 3 responses to “PHP Tutorial – Variables”

Why not let us know what you think by adding your own comment!

  1. shaffy on July 31st, 2010:

    good job

  2. junkiest on November 16th, 2011:

    Nice tutorial…. thanks !!!

  3. Prapulla on August 14th, 2013:

    Best tutorial for PHP thanks