PHP array
An array stores multiple values in one single variable.
In PHP, the array() function is used to create an array.
<?php $pets = array("dog", "cat", "rabbit"); echo $pets[0] .",". $pets[1] .",". $pets[2];
?>
dog,cat,rabbit
An array is a special variable, which can hold more than one value at a time.
If you have a list of student names, storing the names in single variables could like this,
$name1 = "Peter"
$name2 = "Mickle"
$name2 = "Bravo"
However, what if you want to loop through the names and find a specific one? And what if you had 3 names, but 1000?
The solution is to create an array.
An array can hold many values under a single name, and you can access the values by referring to an index number.
There are three different kind of arrays.
- Numeric array – Arrays with a numeric index
- Associative array – Arrays with named keys
- Multidimensional array – Arrays containing one or more arrays
1. PHP Numeric Array
PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.
There are two methods to define indexed array.
$names=array("Peter","Mickle","Bravo","Gayle");
$names[0]="Peter"; $names[1]="Mickle"; $names[2]="Bravo"; $names[3]="Gayle";
Following is the example showing how to create and access numeric arrays.
<?php $names=array("Peter","Mickle","Bravo","Gayle"); foreach($names as $value){echo "Name is $value <br>"; } ?>
Name is Peter
Name is Mickle
Name is Bravo
Name is Gayle
2. PHP Associative Array
Associative arrays are arrays that use named keys that you assign to them.
There are two methods to define associative array.
$age=array("Peter"=>"20","Mickle"=>"26","Bravo"=>"60","Gayle"=>"37");
$age['Peter']="20"; $age['Mickle']="26"; $age['Bravo']="60"; $age['Gayle']="37";
<?php $age=array("Peter"=>"20","Mickle"=>"26","Bravo"=>"60","Gayle"=>"37"); foreach($age as $a=>$a_value){ echo "Key=" . $a . ", Value=" . $a_value; echo "<br>"; } ?>
Key=Peter, Value=20
Key=Mickle, Value=26
Key=Bravo, Value=60
Key=Gayle, Value=37
3. PHP Multidimensional Array
A multidimensional array is an array containing one or more arrays.
$employes=array( array(100,"Erick",10000), array(101,"Nimal",12000), array(102,"Johan",20000) );
<?php $employes=array( array(100,"Erick",10000), array(101,"Nimal",12000), array(102,"Johan",20000) ); for($row=0; $row<3;$row++){ for($col=0; $col<3;$col++){ echo $employes[$row][$col]." "; } echo "<br>"; } ?>
100 Erick 10000
101 Nimal 12000
102 Johan 20000
Comments
Post a Comment