Sunday, June 3, 2012

PHP Arrays, Learn about 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 to use the built-in array function:


$myarray = array('one', 2, '3');
This code creates an array called $myarray that contains three 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 that index in square brackets after the array variable name:

echo $myarray[0]; // Outputs 'one'
echo $myarray[1]; // Outputs '2'
echo $myarray[2]; // Outputs '3'


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 using the assignment operator as usual, but leaving empty the square brackets that follow the variable name:

$myarray[] = 'the fifth element';
echo $myarray[4]; // Outputs 'the fifth element'

Array indices don’t always have to be numbers; that’s 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:

$birthdays['Kevin'] = '1978-04-12';
$birthdays['Stephanie'] = '1980-05-16';
$birthdays['David'] = '1983-09-09';

By PHP with No comments

0 comments:

Post a Comment

    • Popular
    • Categories
    • Archives