PHP Variables
PHP Variables
The syntax for PHP variables is similar to C and most other programming languages. There are
three primary differences:
• Variables in PHP starts with a $ sign, followed by the name of the variable
• The variable name must begin with a letter or the underscore character
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• A variable name should not contain spaces
• Variable names are case sensitive (y and Y are two different variables)
Data Types
PHP has a total of eight data types which we use to construct our variables:
The first five are simple types, and the next two (arrays and objects) are compound - the compound
types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.
PHP has a useful function named var_dump() that prints the current type and value for one or
more variables. Arrays and objects are printed recursively with their values indented to show
structure.
1. Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest type. They
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions, like so:
1
PHP Variables
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal
format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading
0x.
2. Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places
needed. For example, the code:
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);
3. Boolean
They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so:
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
o If the value is a number, it is false if exactly equal to zero and true otherwise.
o If the value is a string, it is false if the string is empty (has zero characters) or is the string "0",
and is true otherwise.
o Values of type NULL are always false.
o If the value is an array, it is false if it contains no other values, and it is true otherwise. For an
object, containing a value means having a member variable that has been assigned a value.
o Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
o Don't use double as Booleans.
Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
2
PHP Variables
4. NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply
assign it like this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you
could just as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties:
5. Strings
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
There are no artificial limits on string length - within the bounds of available memory, you ought to
be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two
ways by PHP:
• Certain character sequences beginning with backslash (\) are replaced with special
characters
• Variable names (starting with $) are replaced with string representations of their values.
3
PHP Variables
String as Document
You can assign multiple lines to a single string variable using here document:
<?php
$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://www.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;
echo <<<END
This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
<br />
END;
print $channel;
?>
<channel>
<title>What's For Dinner<title>
<link>http://www.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
6. Arrays
PHP has essentially one type of array – the associative array (i.e., hash table). Each element in the
array has a key and a corresponding value. Standard arrays (i.e., indexed arrays) can be used in
PHP as well; they are simply associative arrays with integer-indexed keys.
There are three ways to populate an array. The first method is to use the array() function:
The second method is to access the elements directly using the array operator []:
4
PHP Variables
The third method is to use the array operator with no key provided:
This syntax is used less frequently, and has the effect of appending the given value to the array.
As with Perl, arrays are heterogeneous, meaning that the data stored in the array does not need to
be of the same type. For example, $mixedbag contains a string, floating-point value, and a boolean
value. To get the number of elements in an array, use the count() function.
Associative Arrays
Associative arrays work much like their indexed counterparts, except that associative arrays can
have non-numeric keys (e.g., strings). The same three methods for populating indexed arrays apply,
except for the array() function:
The value to the left of the => operator is the key, and the content after it is the corresponding
value.
Multidimensional Arrays
Multidimensional arrays in PHP can be indexed or associative, and are heterogeneous. Consider the
following code which constructs a multidimensional array.
The variable $proglangs is a multidimensional associative array. The first two statements create
indexed arrays of strings, and the last statement creates another associative array.
7. Objects
Object Oriented Programming (OOP) promotes clean modular design, simplifies debugging and
maintenance, and assists with code reuse.
Classes are the unit of object-oriented design. A class is a definition of a structure that contains
properties (variables) and methods (functions). Classes are defined with the class keyword:
class Person
{
var $name = '';
5
PHP Variables
return $this->name;
}
}
Once a class is defined, any number of objects can be made from it with the new keyword, and the
properties and methods can be accessed with the -> construct:
if (is_object($x))
{
// $x is an object
}
8. Resources
Many modules provide several functions for dealing with the outside world. For example, every
database extension has at least a function to connect to the database, a function to send a query to
the database, and a function to close the connection to the database. Because you can have multiple
database connections open at once, the connect function gives you something by which to identify
that connection when you call the query and close functions: a resource.
Resources are really integers under the surface. Their main benefit is that they're garbage collected
when no longer in use. When the last reference to a resource value goes away, the extension that
created the resource is called to free any memory, close any connection, etc. for that resource:
The benefit of this automatic cleanup is best seen within functions, when the resource is assigned to
a local variable. When the function ends, the variable's value is reclaimed by PHP:
function search()
{
$res = database_connect();
$database_query($res);
}
When there are no more references to the resource, it's automatically shut down.
That said, most extensions provide a specific shutdown or close function, and it's considered good
style to call that function explicitly when needed rather than to rely on variable scoping to trigger
resource cleanup.
if (is_resource($x))
{
// $x is a resource
}
Variable Variables
You can reference the value of a variable whose name is stored in another variable.
For example:
$foo = 'bar';
$$foo = 'baz';
After the second statement executes, the variable $bar has the value "baz".
Variable References
In PHP, references are how you create variable aliases. To make $black an alias for the variable
$white, use:
Functions can return values by reference (for example, to avoid copying large strings or arrays):