Low cost ecommerce web development India flash website design

Arrays

An array is a special kind of variable that contains multiple values. If you think

of a variable as a box that contains a value, then an array can be thought of as a

box with compartments, where each compartment is able to store an individual

value.

The simplest way to create an array in PHP is with the built-in array function:

$myarray = array('one', 2, 'three');

This code creates an array called $myarray that contains four values: 'one', 2,

and 'three'. Just like an ordinary variable, each space in an array can contain

any type of value. In this case, the first and third spaces contain strings, while

the second contains a number.

To get at a value stored in an array, you need to know its index. Typically, arrays

use numbers, starting with zero, as indices to point to the values they contain.

That is, the first value (or element) of an array has index 0, the second has index

1, the third has index 2, and so on. In general, therefore, the index of the nth

element of an array is n-1. Once you know the index of the value you're interested

in, you can get that value by placing the index in square brackets following the

array variable name:

echo($myarray[0]); // Outputs "one"

echo($myarray[1]); // Outputs "2"

echo($myarray[2]); // Outputs "three"

You can also use the index in square brackets to create new elements, or assign

new values to existing array elements:

$myarray[1] = 'two'; // Assign a new value

$myarray[3] = 'four'; // Create a new element

You can add elements to the end of an array by using the assignment operator

as usual, except with empty square brackets following the variable name:

$myarray[] = 'the fifth element';

echo($myarray[4]); // Outputs "the fifth element"

Array indices don't always have to be numbers; that is just the most common

choice. You can also use strings as indices to create what is called an associative

array. This type of array is called associative because it associates values with

meaningful indices. In this example, we associate a date with each of three names:

54

Getting Started with PHP

$birthdays['Kevin'] = '1978-04-12';

$birthdays['Stephanie'] = '1980-05-16';

$birthdays['David'] = '1983-09-09';

Now if we want to know Kevin's birthday, we just look it up using the name as

the index:

echo('My birthday is: ' . $birthdays['Kevin']);

This type of array is especially important when it comes to user interaction in

PHP, as we'll see in the next section

website designer freelance ASP PHP ecommerce web developer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110