only one element with a given key.

> Each element also has a value, which is the data associated with the key.

> Each array has a cursor, which points to the current key.

The first three are used regularly; the last one less so. The array cursor is covered later in this chapter in the 'Basic Functions' section, but we look at the other three now. With PHP, your keys can be virtually anything: integers, strings, objects, or other arrays. You can even mix and match the keys so that one key is an array, another is a string, and so on. The one exception to all this is floating-point numbers: You cannot use floating-point numbers as keys in your arrays.

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.

Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату