Array

PHP array are useful to store multiple data using a single variable.

Arrays are common to many programing languages. They are special variables which can hold more than one value, each stored in its own numbered 'space' in the array. Arrays are extremely useful, especially when using WHILE loops.

We can access the stored variables using index of the PHP array .

Indexes to an array element can either a number or a string.

Each item in an array is commonly known as element of the array and can be accessed directly via its index.

Simple and multi-dimensional arrays are supported, and may be either user created or created by another function.

Setting up an array is slightly different to setting up a normal variable. In this example I will set up an array with 3 names in it:

$names[0] = 'name1';

$names[1] = 'name2';

$names[2] = 'name3';

As you can see, the parts of an array are all numbered, starting from 0. To add a value to an array you must specify the location in the array by putting a number in [ ].

Reading from an array is just the same as putting information in. All you have to do is to refer to the array and the number of the piece of data in the array. So if I wanted to print out the third name I could use the code:

echo $names[2];

Main array functions:

  • sizeof($array) count elements in an array
  • current($array) Return the current element in an array
  • sort($array, [, int sort_flags] ) sorts an array. Elements will be arranged from lowest to highest when this function has completed.
  • key() returns the index element of the current array position.

    Example :
    $array = array(

    'elem1' => 'apple',

    'elem2' => 'orange',

    'elem3' => 'grape'};

    // this cycle echoes all associative array

    // key where value equals "apple"

    while ($elem = current($array)) {

    if ($elem == 'apple') {

    echo key($array).'
    ';

    }

    next($array);

    }

    The result displayed would be "elem1"

admin – Thu, 2005 – 07 – 07 11:17