2.2. Variables and Datatypes

So far, you've learned how to output data, as well as how to use variables to a certain extent. Before going any further, let's take a moment to drill down on variables and how they work.

2.2.1. What Is a Variable?

A variable is a keyword or phrase that acts as an identifier for a value stored in a system's memory. This is useful because it allows us to write programs that will perform a set of actions on a variable value, which means you can change the output of the program simply by changing the variable, rather than changing the program itself.

2.2.2. Storing Values in a Variable

PHP lets you store nearly anything in a variable using one of the following datatypes:

String: Alphanumeric characters, such as sentences or names

Integer: A numeric value, expressed in whole numbers

Float: A numeric value, expressed in real numbers (decimals)

Boolean: Evaluates to TRUE or FALSE (sometimes evaluates to 1 for TRUE and 0 for FALSE)

Array: An indexed collection of data (see the "Understanding Arrays" section later in this chapter for more information on this subject)

Object: A collection of data and methods (see Chapter 4 and its section on PHP Data Objects for more information on this subject)

PHP is a loosely typed language, which means it determines the type of data being handled based on a "best guess" principle, as opposed to a strictly typed language such as C, which requires you name datatypes for every variable and function. Consider this code snippet:

$foo = "5"; // This is considered a string
$bar = $foo + 2; // This converts $foo to an integer (outputs 7)

This might seem confusing at first, but it's actually intuitive and eliminates debugging if you enclose a number in quotes accidentally.

2.2.2.1. Understanding Strings

A string is any series of characters enclosed in single (') or double (") quotes, or that you create using special heredoc or nowdoc syntax, which I'll cover in a moment.

Strings have a few characters that will cause problems if you do not escape them with a backslash (). Escaping allows you to use characters in strings that might otherwise cause problems, such as an apostrophe in a string enclosed in single quotes:

$string = 'It's cold outside today!';

If you don't escape the apostrophe in it's, the script has no way of knowing that the apostrophe is part of the string and not the end of it—and your script would fail.

2.2.2.1.1. Single-Quote Syntax

Enclosing a string in single quotes is the simplest way to create a string in PHP. It doesn't expand special characters or variables, but instead delivers them as plain text to the browser.

Let's look at some examples to see how single quotes behave. Add the following into test.php to see how different data is handled:

<?php

    // The <br /> adds a line break in the browser for readability
    echo 'This is a string. <br />';

    echo 'This is a string
    with line breaks. <br />';

    // Special characters, such as the newline (
) character,
    // won't be expanded when in single quotes.
    echo 'This is a string 
 with a newline character. <br />';

    echo 'This string's got an apostrophe. <br />';

    // A backslash doesn't need to be escaped if not escaping a
    // special character.
    echo 'This string has a backslash () in it. <br />';

    echo 'This string has an escaped backslash (\) in it. <br />';

    // Variables will not be expanded in single quotes
    echo 'This $variable will not be expanded. <br />';

?>

The output of this code in a browser looks like this:

This is a string.
This is a string with line breaks.
This is a string 
 with a newline character.
This string's got an apostrophe.
This string has a backslash () in it.
This string has an escaped backslash () in it.
This $variable will not be expanded.

NOTE

Newline characters ( ) don't render in browsers. However, they are visible in the source code of the rendered page, which you can view by choosing View Source from the View menu of your browser.

2.2.2.1.2. Double-Quote Syntax

Strings encased in double quotes behave similarly to strings encased in single quotes but they interpret more special characters, including expanding variables.

Special characters like the new line character ( ) won't affect browser output, but do affect command-line and source-code displays. Use an HTML break tag (<br />) to create a new line in the browser.


You can see the difference achieved by placing strings in double quotes by placing the following code in test.php:

<?php

    echo "This is a string. <br />";

    echo "This is a string
    that spans
    multiple lines. <br />";

    // Apostrophes don't need to be escaped in double quotes
    echo "This string's got an apostrophe. <br />";

// Double quotes will need to be escaped
    echo "This string says, "I need escaping!" <br />";

    // New line characters will be interpreted
    echo "This string has 
 newline 
 characters. <br />";

    // A backslash will be printed if a special character doesn't
    // directly follow it
    echo "This string contains a backslash (). <br />";

    // Variables will be expanded if not escaped
    $variable = "word";
    echo "This string uses a $variable. <br />";

    // A variable can be interpreted as plain text by escaping the
    // dollar sign with a backslash
    echo "This string escapes the $variable. <br />";

?>

The output of this code in a browser looks like this:

This is a string.
This is a string that spans multiple lines.
This string's got an apostrophe.
This string says, "I need escaping!"
This string has newline characters.
This string contains a backslash ().
This string uses a word.
This string escapes the $variable.

String Concatenation

It's often necessary to join two strings together in a script. You accomplish this using the string concatenation operator, a period (.).

You join two strings together by placing a period between them:

<?php
    $foo = "This is a " . "string.";
    echo $foo;
?>

This code creates the following output:

This is a string.

You can concatenate variables as well, as long as they're not of the array or object type:

<?php
    $foo = "This is a ";
    $bar = "string.";
    echo $foo . $bar;
?>

This produces output identical to your previous script:

This is a string.

2.2.2.1.3. Heredoc Syntax

Another option available for handling strings is heredoc syntax, which begins with <<< and an identifier that can be any combination of alphanumeric characters or underscores that don't begin with a digit. You end the string by repeating the identifier on a new line, followed by a semicolon.

You can get a good idea of how heredoc syntax works by examining this example:

$foo = <<<EOD
This is a string created using heredoc syntax.
It can span multiple lines, use "quotes" without
escaping, and it'll allow $variables too.

Special characters are still supported 
 as well.
EOD;

EOD (short for "end of data") is your identifier in this case, but the text you use isn't important. The most important thing to note is that the closing identifier (EOD) is on its own line with no whitespace (any space, tab, or newline characters) before or after it. If this isn't the case, a parse error occurs when you try to run the script.

Functionally, heredoc syntax behaves almost identically to strings encased in double quotes, except that there is no need to escape quotes in the string itself.

2.2.2.1.4. Nowdoc Syntax

Nowdoc syntax is functionally similar to quotes you encase in single quoted strings, and you call it in much the same way that you call heredoc syntax. The difference is that you enclose the identifier in single quotes when you open the string:

$foo = <<<'EOD'

Using nowdoc syntax tells PHP not to parse $variables or newline ( ) characters. According to the PHP manual: Nowdocs are to single-quoted strings what heredocs are to double-quoted strings.[]

[] Quoted from the PHP Manual, "Strings," http://us.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

No variables or special characters within a nowdoc will be expanded; this makes nowdoc syntax ideal for outputting large blocks of PHP code.

NOTE

Nowdoc syntax support was added in PHP 5.3.0—this means that nowdoc syntax won't work in XAMPP out-of-the-box because PHP 5.2 is installed by default.

2.2.2.2. Understanding Integers

An integer is any positive or negative whole number (a number without a decimal value). For example, the numbers 1, −27, and 4985067 are integers, but 1.2 is not.

Because PHP is a loosely typed language, it's not necessary to declare a variable as an integer; however, if you find it necessary, you can explicitly cast, or force, a value as an integer using the following syntax:

$foo = 27; // No quotes around a whole number always means integer
$bar = (int) "3-peat"; // Evaluates to 3
$baz = (int) "seven"; // Evaluates to 0
$bat = (int) "ten 4"; // Evaluates to 0

NOTE

A string value will always evaluate to 0 unless it starts with a numeric value (such as "10 years").

2.2.2.3. Understanding Floating Point Numbers

Floating point numbers (also known as floats or doubles) are numbers with decimal values, or real numbers. This includes numbers such as 3.14, 5.33333, and 1.1.

Note that floating point numbers can produce unexpected results due to the fact that it's impossible to represent all values with a finite number of digits. A good example of this is 1/3, which evaluates to a repeating decimal (0.33333...). You should not use floating point numbers to compare equality for this reason.

2.2.2.4. Understanding Boolean Values

A Boolean value is the simplest type of data; it represents truth, and can contain only one of two values: TRUE or FALSE. It's important to note that the FALSE (not in quotes) Boolean value is different from the "FALSE" string value, and the same goes for TRUE. Boolean values are not case sensitive.

Booleans are very useful when determining if a condition exists. For example, you can use an if-else statement (which I'll cover in a moment) to perform different actions if a condition is TRUE:

if($condition===true)
{
    echo 'The condition is true!';
}
else
{
    echo 'The condition is false!';
}

NOTE

This example uses the comparison operator === to verify that the $condition is TRUE. I'll go over why this is important in the "Operators" section later in this chapter.

2.2.2.5. Understanding Arrays

Arrays are among the most powerful datatypes available in PHP, due to their ability to map information using a key to value pairing. This means that an array can store multiple pieces of information in a single variable, all indexed by key. For instance, if you have a blog entry to store in variables, you would need to do the following if you didn't use arrays:

<?php
    $entryTitle = "Sample Title";
    $entryDate = "April 13, 2009";
    $entryAuthor = "Jason";
    $entryBody = "Today, I wrote a blog entry.";
?>

This can become confusing, especially if the entry needs to be passed to a function for processing. You can use an array to simplify the entry:

<?php
    $entry = array(
        'title' => 'Sample Title',
        'date' => 'April 13, 2009',
        'author' => 'Jason',
        'body' => 'Today, I wrote a blog entry.'
        );
?>

The power of this approach resides in the fact that you now have all of that information stored in one variable, $entry. To access any part of that information, you add the key to the end of the variable in square brackets ([]).

<?php
    echo $entry['title']; // Outputs "Sample Title"
    echo $entry['date']; // Outputs "April 13, 2009"
    echo $entry['author']; // Outputs "Jason"
    echo $entry['body']; // Outputs "Today, I wrote a blog entry."
?>

Arrays can also index information automatically using a numerical index that starts at 0. You access array values that have been indexed automatically using the numeric index as the key, without quotes (e.g., $entry[0]). You can create an automatically indexed array by omitting the keys when you declare the array:

<?php
    $entry = array('Sample Title', 'April 13, 2009', 'Jason',
        'Today, I wrote a blog entry.'),

    echo $entry[0], ' by ', $entry[2];
?>

This snippet produces the following output in a browser:

Sample Title by Jason

NOTE

In programming, counts generally start at 0. This means that the first character in a string is at position 0, not position 1 as you might expect.

When using arrays in strings, you must take an additional step to avoid errors. In order to avoid an error, you must wrap the array variable and key in curly braces ({}). This is known as complex syntax, but not because it's complicated to use; rather, it's called complex because it allows PHP to parse complex statements within a quoted string:

<?php
    $person = array('name' => 'Jason', 'age' => 23);

    echo "This person's name is {$person['name']}
        and he is {$person['age']}.";
?>

Another option when using arrays in double-quoted strings is to leave the single quotes off the array index:

<?php
    $person = array('name' => 'Jason', 'age' => 23);

    echo "This person's name is $person[name]
        and he is $person[age].";
?>

When working with multidimensional arrays (see below), curly braces must be used. Leaving the single quotes off the array indices will behave unexpectedly.


2.2.2.5.1. Multidimensional Arrays

Another cool feature of arrays is their ability to nest within themselves. This creates an array within an array, or a multidimensional array.

Multidimensional arrays are exceptionally powerful because they allow even more information to be stored in one variable, making immense data sets conveniently portable, as you'll see when you start working with databases.

A multidimensional array of people might look something like this:

<?php
    $people = array(
        array('name' => 'Jason', 'age' => 23), // $people[0]
        array('name' => 'Carly', 'age' => 18) // $people[1]
    );

    echo "{$people[0]['name']} has a sister who is
        {$people[1]['age']} years old.";
?>

This script produces the following output:

Jason has a sister who is 18 years old.

Multidimensional arrays can also feature multiple string literal keys:

<?php
    $colors = array(
        'fruits' => array('apple' => 'red', 'plum' => 'purple'),
        'flowers' => array('rose' => 'red', 'violet' => 'blue')
    );

    // Output: An apple is red, and a violet is blue.
    echo "An apple is {$colors['fruits']['apple']}, and a
        violet is {$colors['flowers']['violet']}.";
?>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.240