Arrays in PHP
Arrays in PHP
- Arrays in PHP are a type of data structure that allows us to store multiple
elements of similar or different data types under a single variable.
- By default, the first item has index 0, the second item has item 1, etc.
Example:
<?php
?>
Output:
aaa
bbb
Accessing the 2nd array elements directly:
ABC
XYZ
- Associative arrays are arrays that use named Keys & Values that you assign to
them.
Ex:
<html>
<body>
<pre>
<?php
$car = array("College"=>"NHC", "Class"=>"BCA", "SNO"=>420);
var_dump($car);
?>
</pre>
</body>
</html>
Output:
array(3)
{
["College"]=>
string(3) "NHC"
["Class"]=>
string(3) "BCA"
["SNO"]=>
int(420)
}
3. Multidimensional Arrays:
<?php
$tbl = [ [1,2,3,4],
[10, 20, 30, 40],
[100, 200, 300, 400]
];
OUTPUT:
Value at [2], [2] :300
EX:
<?php
$students = array(
array("name"=>"aaa", "age"=>39),
array("name"=>"bbb", "age"=>49),
array("name"=>"ccc", "age"=>59)
);
echo $students[0]["name"];
echo $students[0]["age"] . "<br>";
echo $students[1]["name"];
echo $students[1]["age"] . "<br>";
echo $students[2]["name"];
echo $students[2]["age"];
?>
output:
aaa39
bbb49
ccc59