PHP Tutorials

Variable Types

Variable types, which are handled automatically by PHP, tell PHP what kind of value it’s working with. To put things in perspective, think about what you know about certain values. Cat, for example, is text. You can’t multiply cat by cat because they’re not numbers, they’re text. However, 5 and 5 can be multiplied to make 25. They’re numbers, so it works.

PHP recognizes a value as belonging to a certain data type depending on the characteristics of the value. The following sections describe certain characteristics and behaviors for each data type.

Integers
An integer is any numeric value that does not have a decimal point, such as the following:

5 (five)

–5 (negative five)

0123 (preceded by a zero; octal representation of decimal number 83)

0×12 (preceded by 0x; hexadecimal representation of decimal number 18)

The last two values on the list are somewhat advanced topics and are rare. They are presented for your information so you know what you’re dealing with if you ever encounter this notation. It is important, however, for you to know that preceding a number with a zero (which may seem insignificant) is going to produce unexpected results. The previous example, for instance, proves this point: 123 is much different than 83 (which is 0123 octal).

NOTE

PHP does have limitations within the integer type. On 32-bit platforms, integers are limited to be 32-bit numbers (–2,147,483,648 to 2,147,483,648); on 64-bit platforms integers are limited to be 64-bit numbers (–9,223,372,036,854,775,808 to 9,223,372,036,854,775,808). This generally doesn’t become a problem, but if you attempt to handle extremely large values (negative or positive), you might find that results aren’t as expected. This is a limitation of all programming languages and there is information on the PHP Web site for using larger numbers, should you have the need.

Floating-Point Numbers
A floating-point number (commonly referred to simply as a float or double, which, in PHP, are exactly the same thing) is a numeric value with a decimal point.

The following are all floating-point values:

5.5

.055e2 (scientific notation for .055 times 10 to the second power, which is 5.5)

19.99

The second example is a float represented in scientific notation. The e, as is often the case on graphing calculators, means “times 10 to the”. It is followed by whatever power 10 should be raised to in order to put the decimal wherever you want it. Thus, .055e2 is the same as .055 times 100, which is 5.5.

Floats also have limitations—floats are accurate enough for general-purpose use, but if you need to store a number with an extremely long decimal value, you will need to look into the arbitrary precision math functions (BCMath or GMP) on the PHP Web site.

Also, because of these limitations, you must realize that a float isn’t always exactly what you think it is. For example, 1/3 can only be represented as .33333333… in the computer’s memory; the 3’s repeat forever, so it’s impossible to be completely accurate. It’s best to decide on how much precision you desire (for instance, if dealing with money, you’d choose 2 decimal places) and keep in mind that your decimals are no more accurate than that. Thus, you will reduce your chances for strange results when doing calculations (which is discussed in Chapter 4, “Arithmetic”).

Arrays
Arrays are a little different than the numeric data types discussed so far. Arrays can be thought of as lists of variables, all contained within one variable. These variables can contain values of any data type, including being arrays themselves. For example, if five people are involved in a task, their names could be stored in a five-element array, with one element for each person. The people on the task, represented collectively by the array, would each have their information stored in separate variables within the array.

Array Indexing
The names could then be retrieved using array indexing—adding a subscript (or location within the array) to the end of an array’s name to retrieve the value of that element. (An element is a single variable contained within an array.)

The following example demonstrates the construction of an array containing five names, then printing each name on a separate line:



<?php
/* ch02ex03.php – demonstration of arrays */

$namesArray = Array('Joe', 'Bob', 'Sarah', 'Bill', 'Suzy');

echo "$namesArray[0]
";
echo "$namesArray[1]
";
echo "$namesArray[2]
";
echo "$namesArray[3]
";
echo "$namesArray[4]
";

?>


NOTE

The
tags are given here to separate each element of the array on a separate line.

It’s important to notice that the first element of an array is given by the subscript 0 and not 1. While this may seem awkward, it is fairly common in programming languages because of the way arrays are handled in memory.

TIP

Why is the first index of an array always 0? In many languages, namely C (because most of the other languages that do it are based off C), there’s a very good reason. An array would be given an area of memory when it was created, and in that area of memory, the array’s elements are stored in order. The array name only contains the address of the first element of the array. Thus, the index given would be the offset from the address; that is, the index shows how many positions to move ahead in memory.

So, the first element of the array would be indexed at its address plus 0, the second would be indexed at the address of the first plus 1, and so on. This behavior has made its way into most of today’s languages.

Arrays can be constructed as shown previously, or alternatively by assigning a value to a new element, which can either be automatically added to the end or inserted at an explicitly specified index within the array.

The following example demonstrates the use of empty brackets after an array to add new elements and also explicitly defines a certain element in an array:



$namesArray = Array('Joe', 'Bob', 'Sarah', 'Bill', 'Suzy');
$namesArray[] = 'Rachel'; // adds 'Rachel' as $namesArray[5]
$namesArray[3] = 'John'; // replaces 'Bill' with 'John'

Generally, the Array() function is used to create an array for which all values are hard-coded; the empty brackets construct is used when the array will have an unknown number of variables added to it; and the specific subscript method is used whenever a specific value needs to be accessed or changed.

Strings
Strings are values that contain text—anything from one character to a whole string of characters (hence the name). For example, a sentence such as “This is a string” is a string value.

There are two types of strings: those that are single-quoted and those that are double-quoted.

Single-quoted strings are always interpreted just as they are. For example, to use “My variable is called $myVariable” as a string, use the statement found in the following example:



<?php
/* ch02ex04.php – shows use of single-quoted strings */

echo 'My variable is called $myVariable';

?>


The output from this example is

My variable is called $myVariable

As you may have noticed from the echo statements found earlier in this chapter, double-quoted strings are interpreted so that variables are expanded before they are actually stored as a value. Consider the following example:




<?php
/* ch02ex05.php – shows use of double-quoted strings */
// Do single-quote assignment and output result
$myVariable = 'My variable is called $myVariable';
echo $myVariable;

// Move to new line
echo '
';

// Do double-quote assignment and output result
$myVariable = "My variable is called $myVariable";echo $myVariable;

?>


The output from this example is

My variable is called $myVariable
My variable is called My variable is called $myVariable

The first assignment works just as the single-quoted assignment earlier: The text is assigned just as you see it. Thus, the first line of output shows the string just as it appears in the code.

However, the second assignment uses a double-quoted string, so the string is interpreted before it is stored in the variable. Thus, $myVariable is expanded using its current value (that of the first assignment), and then the new value is stored in the variable, yielding the string found on the second line of output.

Character Escaping
Some characters, such as the dollar sign, have special meaning within strings. In addition, sometimes you need to include quotes within your strings, which would typically signal the end of the string.

To avoid this, we use character escaping, which tells PHP to interpret a character as a literal part of the string instead of a special character (one that would signal a variable or the end of a string).

To escape a character, precede it with a backslash, like this:

\char

Here, char is any single character, such as a dollar sign or quote.

The following example uses character escaping to include $strSmall’s name and its contents surrounded by quotes inside the string $strBig:



<?php
/* ch02ex06.php – demonstrates character escaping */
$strSmall = "John Smith";

$strBig = "The name stored in \$strSmall is \"$strSmall\".";
echo $strBig;

?>

Take time to study the assignment of $strBig, as it demonstrates both the escaping of the dollar sign and of quote characters, both of which are interpreted literally as part of the string when encountered in their escaped form.

Thus, the output of the above program is

The name stored in $strSmall is “John Smith”.

String Indexing
Strings have an indexing feature that makes them much like an array of letters. To find the letter at a given position, use the following syntax:



$string{index}

Here, $string should be any string variable and index should be a position within that string for which you want the letter.



For example, take a look at the following program:


<?php
/* ch02ex07.php – demonstrates string indexing */

// Assign a name to $strName
$strName = "Walter Smith";

// Output the fifth letter of the name
echo $strName{4};

?>

NOTE

The index for the fifth letter is actually 4 because indexing of strings, like that of arrays, begins with 0.

Objects
Objects are a powerful method of program organization. They are essentially what people are talking about when they refer to OOP or Object-Oriented Programming. Objects (and their definitions, called classes) are discussed in depth in Chapter 12, “Using Include Files (Local and Remote).”

Filed under: Chapter 2 @ 10:21 pm

Scope

Scope refers to the lifetime of any particular variable. Variables are available only in certain areas of a program, depending on where they are declared. The main scope, known as the global scope, contains most of the variables you declare. So far, all of the variables we’ve declared have belonged to the global scope. Later, when we get to functions, the global scope will contain fewer of your variables.

Other parts of your program have their own scopes. The main reason behind this is to prevent the accidental changing of a variable. For example, in any given program, you might create a variable called $temp. A variable like this might be used while you perform some kind of processing algorithm.

However, what if, in the course of that processing somewhere, the value of $temp was changed by code located in some other function or even in some other file? For example, look at the following code:



// Code segment – NOT a working example
$temp = "This string is being processed.";

for ($x = 1; $x <= strlen($temp); $x++)
{
$part = substr($temp, $x, 1);
doSomething($part);
}

Don’t worry about trying to figure out exactly what the code does. It doesn’t really have much use, as it is; doSomething() undefined. Either way, there’s only one place where it appears $temp is being assigned a value—at the very beginning of the segment. And luckily, that’s the way it is. Without variable scope, though, doSomething() could’ve had an assignment to $temp in it and we would never know. Finding a bug in code without a variable scope can take weeks of persistent debugging time by an experienced programmer or even a team of experienced programmers.

Variable scope is basically divided between the global scope and individual functions; each (the global scope and each function) has a scope of its own, and, thus, no variables will be overwritten by a function or segment of code that isn’t supposed to do so.

Functions

Class member functions

Filed under: Chapter 2 @ 10:24 pm

Type Casting

Type casting is specifying the type that a certain variable should be evaluated as for a particular statement. This is useful, for example, if you want to use just the integer portion of a floating-point number. Since integers aren’t allowed to have a decimal point, the decimal point and everything after it would be dropped in such a conversion.

NOTE

The first three are probably the most common. However, casts to array or object types are also supported.

If a cast is made to an array, the result is an array whose first element is the value of the variable before it was cast. If a cast is made to an object, an object is created with a member variable called scalar that contains the value of the variable before it was cast.

Casts of this sort are uncommon and doing so is discouraged.

Necessity of Type Casting
It’s not usually necessary to typecast a variable. Most of PHP’s functions will do this for you; PHP is said to handle types automatically.

Thus, type casting comes in handy occasionally for things such as converting from integers to doubles. It isn’t something you’ll use a lot, but when you do use it, it’s a lot quicker and easier than any other method would be.

Syntax
To typecast a variable, specify the type you wish the variable to become in parentheses, followed by the variable, as follows:

(type) $variable

NOTE

Since PHP ignores whitespace, spaces can be included between the parentheses and the type, as desired. Also, at your discretion, the type may be placed right next to the variable, without a space in between the two. There are no real style guidelines or concerns here, so what you do is up to you; basically, try to use what you find is most readable.

Type casting can be done between any of the following types (types listed with the same bullet point are the same):

(int) or (integer)

(real), (double), or (float)

(string)

(array)

(object)

The following example performs a type cast:



The first echo statement in this program shows that the decimal value 5.5 was really assigned to $myFloat. The second statement shows what the value of $myFloat is after a type cast to an integer.

However, it is important to note that this type-casting operation did not change the value of $myFloat as it is stored in the variable; if you want to change the type of the variable itself, you can assign the type-cast variable to itself, as follows:



This program’s output is simply:

5

NOTE

Assigning 5.5 to $myFloat again would cause PHP to automatically set the type of $myFloat back to float. Types may change commonly, so don’t rely on a type being preserved for a variable after type casting.

Filed under: Chapter 2 @ 10:25 pm
« Previous PageNext Page »

Powered by WordPress