Oct
30
Posted on 30-10-2007
Filed Under (Tutorial) by chintan

An array can store one or more values in a single variable name.

What is an array?

When working with PHP, earlier or later, you might want to create many similar variables.

In place of having many similar variables, you can store the data as elements in an array.

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

There are three different types of arrays:

1 Numeric array – An array with a numeric ID key

2 Multidimensional arrays – An array containing one or more arrays

3 Associative arrays – An array where each ID key is associated with a value

(1) Numeric Arrays

A numeric array stores each part with a numeric ID key.

There are different ways to create a numeric array.

Example

In this example the ID key is automatically assigned:

$names = array(“Akki”,”Jimmi”,”Joy”);

In this example we assign the ID key manually:

$names[0] = “Akki”;

$names[1] = “Jimmi”;

$names[2] = “Joy”;

The ID keys can be used in a script:

<?php

$names[0] = “Akki”;

$names[1] = “Jimmi”;

$names[2] = “Joy”;

echo $names[1] . ” and ” . $names[2] .

” are “. $names[0] . “’s partner”;

?>

The code above will output:

Jimmi and Joy are Akki’s partner

(2)Multidimensional Arrays

In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

Example

In this example we create a multidimensional array, with automatically assigned ID keys:

$families = array

(“Griffin”=>array

( “Akki”,”Pats”, “Maks”),

“Jimmi”=>array

(“Glenn” ),

“Brown”=>array

(“Cleveland”, “Loretta”,”Junior”));

The array above would look like this if written to the output:

Array

([Griffin] => Array
([0] => Akki

[1] => Pats

[2] => Maks )

[Jimmi] => Array

( [0] => Glenn )

[Brown] => Array
( [0] => Cleveland

[1] => Loretta

[2] => Junior))

3 Associative Arrays

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

When storing data about specific named values, a numerical array is not always the best way to do it.

With associative arrays we can use the values as keys and assign values to them.

Example

In this example we use an array to assign ages to the different persons:

$ages = array(“Akki”=>21, “Jimmi”=>18, “Joy”=>20);

This example is the same as example 1, but shows a different way of creating the array:

$ages['Akki'] = “21″;

$ages['Jimmi'] = “18″;

$ages['Joy'] = “20″;

The ID keys can be used in a script:

<?php

$ages['Akki'] = “21″;

$ages['Jimmi'] = “18″;

$ages['Joy'] = “20″;

echo “Akki is ” . $ages['Akki'] . ” years old.”;

?>

The code above will output:

Akki is 21 years old.

Share These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • Live
  • StumbleUpon
  • Technorati
  • YahooMyWeb
(0) Comments    Read More   
Post a Comment

You must be logged in to post a comment.