PHP arrays
* In PHP, there are three kind of arrays:
* 1)Numeric array - An array with a numeric index
* 2)Associative array - An array where each ID key is associated with a value
* 3)Multidimensional array - An array containing one or more arrays
1)Numeric Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
2. In the following example we assign the index manually:
2) 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:
*
key value
| |
Example 2
This example is the same as example 1, but shows a different way of creating the array:
*
key value
* | | */
//The ID keys can be used in a script:
* 1)Numeric array - An array with a numeric index
* 2)Associative array - An array where each ID key is associated with a value
* 3)Multidimensional array - An array containing one or more arrays
1)Numeric Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$array1 = array(3,5,7,2); echo $array1[0]." "; $array2 = array(4,"dantha" ,"brown" ,array("x","y","z")); echo $array2[3][2]." "; $array2[3] = "Cat"; echo $array2[3]." ";
2. In the following example we assign the index manually:
$cars[0]="Honda"; $cars[1]="Nissan"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0]." and ".$cars[1]." are Japanese cars";
2) 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:
*
key value
| |
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:
*
key value
* | | */
$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";
//The ID keys can be used in a script:
echo "Peter is " . $ages['Peter'] . " years old."; $array3 = array("first_name" => "Dantha" ,"last_name" => "Elvitigala"); echo $array3["first_name"]; echo " "; $array4 = array(1 => "Dantha" ,2 => "Elvitigala"); echo $array4[1]; echo " "; echo count($array4); // count array elements
Comments
Post a Comment