- An array can store one or more values in a single variable name.
- When working with php you might want to create many similar variables instead of having many similar variables, you can store the data as elements in an array.
- Each element in the array has its on id so that it can be easily access.
There are three different kind of array
- Numeric array : An array with 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 array
Numeric array stores each element with a numeric ID key. There are different way to create a numeric array.
Example
In this example the id key is automatically assign.
<?php
$arr=array("php","java","j2me");
foreach($arr as $key=>$value)
{
echo "key is $key & value is ".$value."<br/>";
}
?>
Output
key is 0 & value is php
key is 1 & value is java
key is 2 & value is j2me
key is 1 & value is java
key is 2 & value is j2me
Ø Associative array
An associative array, each ID key is associated with a value when storing data above specified a name value, a numeric array is not always the best way to do it.
With associative array we can use the value as key and assign value to them
Example
<?php
$arr = array("php"=>"99","java"=>"95","j2me"=>"90");
foreach($arr as $key=>$value)
{
echo "$key $value <br/>";
}
?>
Output
Php 99
java 95
j2me 90
java 95
j2me 90
Ø multidimensional array
In 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 in this example we create a multidimensional array with an automatically assign ID key.
Example
<?php
$arr = array("sem1"=>array("cs","c","html"),"sem2"=>array("ds","coa"));
foreach($arr as $key=>$value)
{
echo $key."<br/>";
foreach($value as $val)
{
echo " ".$val."<br/>";
}
}
?>
Output
Sem1
Cs
C
html
sem2
ds
sem2
ds
coa
No comments:
Post a Comment