There are three different kind of arrays:
- Numeric array - An array with a numeric ID key
- Associative array - An array where each ID key is associated with a value
- Multidimensional array - An array containing one or more arrays
Numeric Arrays
A numeric array stores each element with a numeric ID key. There are different ways to create a numeric array.
Example 1
In this example the ID key is automatically assigned:
Code:
$names = array("John","Paul","Steve");
Example 2
In this example we assign the ID key manually:
Code:
$names[0] = "John"; $names[1] = "Paul"; $names[2] = "Steve";
Code:
<?php $names[0] = "John"; $names[1] = "Paul"; $names[2] = "Steve"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s Friends"; ?>
Paul and Steve are John's Friends
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 1
In this example we use an array to assign ages to the different persons:
$ages = array("John"=>32, "Paul"=>30, "Steve"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:
Code:
$ages['John'] = "32"; $ages['Paul'] = "30"; $ages['Steve'] = "34";
Code:
<?php $ages['John'] = "32"; $ages['Paul'] = "30"; $ages['Steve'] = "34"; echo "John is " . $ages['John'] . " years old."; ?>
John is 32 years old.
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:
Code:
$families = array ( "Griffin"=>array ( "John", "Lois", "Megan" ), "Paul"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
Code:
Array ( [Griffin] => Array ( [0] => John [1] => Lois [2] => Megan ) [Paul] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) )
No comments:
Post a Comment