PHP Array
Array is used to store a collection of values at one place instead of creating different variables.
PHP Have 2 types of arrays.
- Indexed Arrays
- Associative Arrays
Define Indexed Array
In PHP arrays are defined by array() method or by square brackets
<?php
//Numeric Index Array
$colors=array("black","white","green");
//another way of defining array
$fruit[]="Apple";
$fruit[]="Orange";
$fruit[]="Mango";
?>
Indexed Array Example
<?php
//Numeric Index Array
$colors=array("black","white","green");
echo "i like ".$colors[0]." color and my country flag contains ".$colors[1]." & ".$colors[2]." Colors";
?>
Manually Assigned Indexed Array Example
PHP allow manually assigned Index to an array
<?php
//Manually assign Array Index
$colors[1]="Black";
$colors[2]="White";
$colors[3]="Green";
echo "i like ".$colors[1]." color and my country flag contains ".$colors[2]." & ".$colors[3]." Colors";
?>
Loop Through Indexed Array Example
<?php
//loop through Indexed Array
$Cities=array("Lahore","Dubai","Jinan");
for($a=0;$a<3;$a++){
echo $Cities[$a]."<br>";
}
?>
Associative Array Example
Associative Arrays contains Alphanumeric Index instead of Numeric Index.
<?php
//Associative Array
$height=array("Qasim"=>5.7,"Fasial"=>5.5,"Kamran"=>6);
echo "Qasim height is ".$height['Qasim']." Feet
";
echo "Fasial height is ".$height['Fasial']." Feet
";
echo "Kamran height is ".$height['Kamran']." Feet
";
?>
Associative Array with Foreach Loop Example
Foreach loop is designed for Arrays and it work very fine with Associative Arrays.
<?php
//Associative Array via ForeachLoop
$height=array("Qasim"=>5.7,"Fasial"=>5.5,"Kamran"=>6);
foreach($height as $name=>$value){
echo $name." height is ".$value." Feet
";
}
?>