An array is a special variable which can hold more than one value at a time
In php, the array( ) function is used to create an array.
Eg. array( );
There are three types of array.
:- numeric arrays can store numbers, Strings, and any object but their index will be prasented by numbers. By default array index starts from zero.
Traverse array using foreach loop
Example : First
Traverse array using for loop
Associative array :-
The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index.
Associative array will have their index as string so that you can establish a strong association between key and values.
Associative arrays are arrays that use named keys that you assign to them.
Note :- Don?t keep associative array inside double quote while printing otherwise it would not return any value.
in associate array, we use => symbol.
There are two ways to define associative array:
Traversing PHP Associative Array
using foreach to traverse an associative array
Example : Using foreach Loop.
Example : Using for Loop.
PHP Multidimensional Array
Values in the multidimensional array are accessed using multiple index. A multidimensional array is an array that contains at least one other array as the value of one of the indexes.
It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column.Example :
$emp = array
(
array(1,"mahtab",200000),
array(2,"habib",60000),
array(3,"kalam",80000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Example :
$marks = array(?mahtab? => array(?phy? => 40, ?che? => 35, ?math?=>50), ?alam?=> array(?phy? => 30, ?che? => 32, ?math?=>60));
echo ?marks for mahtab in physics :?;
echo $marks[?mahtab?][?phy?].?<br/>?;
echo ?marks for alam in math :?;
echo $marks[?alam?][?math?].?<br/>?;
?>
Traversing PHP Associative Array
$salary=array("Mahtab"=>"550000","Asif"=>"250000","Alka"=>"200000");
foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
}
?>
Previous
Next
Trending Tutorials