Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ‘[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Note: $this is a special variable that can’t be assigned.

$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"

$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; // valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.

By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable’s value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, “becomes an alias for” or “points to”) the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs ‘My name is Bob‘ twice:

$foo = 'Bob'; // Assign the value 'Bob' to $foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $bar;
echo $foo; // $foo is altered too.

One important thing to note is that only named variables may be assigned by reference.

$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.

function test()
return 25;

$bar = &test(); // Invalid.

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used – booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo()) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

// Unset AND unreferenced (no use context) variable; outputs NULL

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;

// Array usage; outputs array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")

// Object usage; creates new stdClass object (see
// Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

82% de los trabajadores usa sus dispositivos tecnológicos en el trabajo Cada vez crece más la tendencia Byod (Bring your own device) al punto de que es un fenómeno prácticamente irreversible. Los dispositivos móviles co...
¿Quieres saber cómo seremos los seres humanos dentro de 1.000 años?.. mira este video Dentro de 1.000 años los seres humanos seremos unas criaturas muy diferentes. Este video muestra cómo el cambio climático, la inteligencia art...
Monitoriza tu presencia en la Web con Google Mantener el control sobre la información que ofrecemos de nosotros mismos en Internet es una tarea importante, cuyo mejor o peor cumplimiento puede ...
Ranking Distribuciones Linux Septiembre 2012 Tal y como viene sucediendo durante los últimos meses el Ranking Distribuciones Linux es de nuevo encabezado por los diferentes sabores que componen l...
Total-Based Shipping Opencart Module This extension allows you to set advanced shipping rates for your shop, and can be calculated by Total with Postal Code and Category support. General...
RIM launches new Blackberry Bold Research In Motion, casa matriz de los BlackBerry aprovechó el BlackBerry World que se realiza en la ciudad de Orlando, en Estados Unidos, para dar a ...
Validaciones de variables en PHP, caso isset En la vida real de cualquier programador un dolor de cabeza es las validaciones de tipos de datos, vamos a ver algunas de ellas en el lenguaje PHP, en...
Tipos de variables en Javascript JavaScript divide los distintos tipos de variables en dos grupos: tipos primitivos y tipos de referencia o clases. Tipos primitivos Jav...
Intercambio de enlaces en la promoción en buscadores Atraer tráfico de gente buscando información relacionada con la temática de tu Web, es importante si quieres que tu negocio online empiece con buen ...
The Google Panda process Google Panda was built through an algorithm update that used artificial intelligence in a more sophisticated and scalable way than previously possible...
Variables in PHP
Tagged on: