Variables and data types in PHP

Variables

Variables are used to store data during the execution of a script. When you define a variable and assign it to a value you practically name the value. When you need exactly that value later you can access it in the script with its name.

A variables name is changeable. If you assign a value to a variable that already exists the new value will override the previous value. The name of a variable is assigned to a value with the assignment operator, which is symbolized by a simple equal sign =. This is how an assignment is basically structured:

name = value;

Fundamental syntax

Valid variable names in PHP are introduced with a dollar sign $. The first character after $ can only be a letter or an underscore _. After that you can use any combination of letters, numbers and underscores.

Valid variables are:

Invalid variables are:

<?php
$30testVariable = "Text"; //stars with a number
$%%%%% = "1234"; //forbidden characters
?>

As long as a script is being executed and a variable hasn't been removed with the unset command we can change its value. PHP differentiates between uppercase and lowercase letters. $VAR, $Var and $var therefore are three different variables.

You can also assign a variables value to another variable.

Data types

Maybe you noticed that we handled the assignment of variables in our previous examples differently. We defined some values inside quotes "" but we also defined some values without them. The reason for that are the different data types that these values have.

By defining the data types you also specify which operations you can use to process the data. You can't add "Text" to 5 because you generally can't calculate with sentences.

In PHP there are 8 different data types.

Identifier Data type Examples & Description
Character strings String 'a', 'text', 'a great sentence'
Integer values Integer 1, 2, 3, 40, 100, 1200
Floating-point numbers Float/Double 1.4, 2.5, 5.999, 14.49
Boolean values Boolean true, false
Arrays Array Multi-value data type
Objects Object Multi-value data type
Resources Resource Reference to external sources
Null Null Type for variables without a value


Continue to part 3







Comment