Выбрать главу

There are two ways of adding values to an array: with the [] operator, which is unique to arrays, and with the array() pseudo-function. You should use [] when you want to add items to an existing array and use array() to create a new array.

To sum all this up in code, Listing 27.2 shows a script that creates an array without specifying keys, adds various items to it both without keys and with keys of varying types, does a bit of printing, and then clears the array.

LISTING 27.2 Manipulating Arrays

<?php

 $myarr = array(1, 2, 3, 4);

 $myarr[4] = "Hello";

 $myarr[] = "World!";

 $myarr["elephant"] = "Wombat";

 $myarr["foo"] = array(5, 6, 7, 8);

 echo $myarr[2];

 echo $myarr["elephant"];

 echo $myarr["foo"][1];

 $myarr = array();

?>

The initial array is created with four elements, assigned the values 1, 2, 3, and 4. Because no keys are specified, PHP automatically assigns keys for us starting at 0 and counting upward—giving keys 0, 1, 2, and 3. Then we add a new element with the [] operator, specifying 4 as the key and "Hello" as the value. Next, [] is used again to add an element with the value "World!" and no key, and then again to add an element with the key "elephant" and the value "wombat". The line after that demonstrates using a string key with an array value — an array inside an array (a multidimensional array).

The next three lines demonstrate reading back from an array, first using a numeric key, then using a string key, and then using a string key and a numeric key. Remember, the "foo" element is an array in itself, so that third reading line retrieves the array and then prints the second element (arrays start at 0, remember). The last line blanks the array by simply using array() with no parameters, which creates an array with elements and assigns it to $myarr.

The following is an alternative way of using array() that enables you to specify keys along with their values:

$myarr = array("key1" => "value1", "key2" => "value2", 7 => "foo", 15 => "bar");

Which method you choose really depends on whether you want specific keys or want PHP to pick them for you.

Constants

Constants are frequently used in functions that require specific values to be passed in. For example, a popular function is extract(), which takes all the values in an array and places them into variables in their own right. You can choose to change the name of the variables as they are extracted by using the second parameter— send it 0 and it overwrites variables with the same names as those being extracted, send it 1 and it skips variables with the same names, send it 5 and it prefixes variables only if they exist already, and so on. Of course, no one wants to have to remember a lot of numbers for each function, so you can instead use EXTR_OVERWRITE for 0, EXTR_SKIP for 1, EXTR_PREFIX_IF_EXISTS for 5, and so on, which is much easier.

You can create constants of your own by using the define() function. Unlike variables, constants do not start with a dollar sign, which makes the code to define a constant look like this:

<?php

 define("NUM_SQUIRRELS", 10);

 define("PLAYER_NAME", "Jim");

 define("NUM_SQUIRRELS_2", NUM_SQUIRRELS);

 echo NUM_SQUIRRELS_2;

?>

That script demonstrates how you can set constants to numbers, strings, or even the value of other constants, although that doesn't really get used much!

Comments

Adding short comments to your code is recommended and usually a requirement in larger software houses. In PHP you have three options for commenting style: //, /* */, and #. The first option (two slashes) instructs PHP to ignore everything until the end of the line. The second (a slash and an asterisk) instructs PHP to ignore everything until it reaches */. The last (a hash symbol) works like // and is included because it is common among shell scripting languages.

This code example demonstrates the difference between // and /* */:

<?php

 echo "This is printed!";

 // echo "This is not printed";

 echo "This is printed!";

 /* echo "This is not printed";

 echo "This is not printed either"; */

?>

It is generally preferred to use // because it is a known quantity. On the other hand, it is easy to introduce coding errors with /* */ by losing track of where a comment starts and ends.

NOTE

Contrary to popular belief, having comments in your PHP script has almost no effect on the speed at which the script executes. What little speed difference exists is wholly removed if you use a code cache.

Escape Sequences

Some characters cannot be typed, and yet you will almost certainly want to use some of them from time to time. For example, you might want to use an ASCII character for newline, but you can't type it. Instead, you need to use an escape sequence: \n. Similarly, you can print a carriage return character with \r. It's important to know both of these because on the Windows platform, you need to use \r\n to get a new line. If you do not plan to run your scripts anywhere else, you need not worry about this!

Going back to the first script we wrote, you will recall it printed 2010 because we added 10 + 10 and then 10 + 0. We can rewrite that using escape sequences, like this:

<?php

 $i = 10;

 $j = "10";

 $k = "Hello, world";

 echo $i + $j;

 echo "\n";

 echo $i + $k;

 echo "\n";

?>

This time PHP prints a new line after each of the numbers, making it obvious that the output is 20 and 10 rather than 2010. Note that the escape sequences must be used in double quotation marks because they do not work in single quotation marks.

Three common escape sequences are \\, which means "ignore the backslash"; \", which means "ignore the double quote"; and \', which means "ignore the single quote." This is important when strings include quotation marks inside them. If you had a string such as "Are you really Bill O'Reilly?", which has a single quotation mark in, this code would not work:

<?php

 echo 'Are you really Bill O'Reilly?';