Friday, September 25, 2009

Php Arrays

An array is a data structure that stores one or more values in a single value.An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible

Each element in the array has its own index so that it can be easily accessed.

In PHP, there are three kind of arrays:

* Numeric array - An array with a numeric index
* Associative array - An array where each ID key is associated with a value
* Multidimensional array - An array containing one or more arrays

Numeric array
A numeric array stores each array element with a numeric index.

Example:

General:
$example=array("abc",123,"xyz","test");

In the following example we assign the index manually:
$example[0]="abc";
$example[1]=123;
$example[2]="xyz";
$example[3]="test";

we call the Indexed array as
echo $example[0] . " and " . $example[1] ;

or

foreach ($example as $i => $value) {
echo $value;
}

Associative Array
An associative array, each ID key is associated with a value.

Initializing an Associative Array

The following code creates an associative array with product names as keys and prices as values.

$prices = array( 'test1'=>100,
'test2'=>10, 'test3'=>4,'test4'=>5 );

There are different ways we can initialize the associative array

$prices = array( 'test1'=>100 );
$prices['test2'] = 10;
$prices['test3'] = 4;

Using Loops with Associative Arrays
Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. We can use the foreach loop or the list() and each() constructs.

The foreach loop has a slightly different structure when using associative arrays. We can use it exactly as we did in the previous example, or we can incorporate the keys as well:

foreach ($prices as $key => $value)
echo $key.'=>'.$value.'
';

The following code lists the contents of our $prices array using the each() construct:

while( $element = each( $prices ) )
{
echo $element[ 'key' ];
echo ' - ';
echo $element[ 'value' ];
echo '
';
}

Some of the Usefull methods are:

$b = array_values($a);

This will assign the the array a to the b and b will be considered as a array.

unset($arr[5]);
This will removes the particular element in the array

0 comments:

Post a Comment