PHP Variables Tutorial

This video tutorial covers PHP variables.

What is a Variable?

Variables are used to store information in form of values like text strings, numbers, arrays or other variables.

All variables in PHP must start with a dollar sign ($) symbol. The dollar sign is not technically part of the variable name, but it is required as the first character of the variable for the PHP parser to recognize it as a variable.

Declaring a Variable

When a variable is declared in PHP, that variable can be used over and over in your PHP script.

The PHP code below shows you how to declare a variable.

<?php $variable_name = variable; ?>

PHP is a Loosely Typed Language

PHP is a loosely typed language, this means that a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data, depending on the value of the variable.

In a strongly typed programming language, for example Java and C#, you have to specify the type of data that a variable will hold.

Naming Rules for Variables

  • 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 _ )
  • A variable name can not contain any spaces within the name

Examples

The examples below show you how to declare string variables.

<?php $string_1 = 'first string'; $string_2 = 'second string'; <p> echo $string_1; echo "<br />"; echo $string_2; </p> ?>

The example above would display the text below.

first string
second string

The example below show you how to declare numeric variables.

<?php $number = 10; <p> echo $number; </p> ?>

The example above would display the text below.

10